一,火车站卖票,假设4个窗口同时卖100张票。
那么4个窗口就代表4个线程,同时工作,任务只有一个,那就是卖票。
要是不加锁,就会出现下面情况:
数据很紊乱,不能确保安全输出,就被其他线程抢走了CPU
所以我们需要加上锁来确保数据的同步
//卖票
class SaleTickets extends Thread{
private int tickets=100;
Object lock=new Object();
//一个任务
public void run(){
while(true){
synchronized (lock) {
if(tickets>0){
tickets--;
System.out.println(Thread.currentThread().getName()+"还剩"+tickets+"张票");}
if(tickets==0){
break;
}
}
}
}
}
public class Test {
public static void main(String[] args) {
SaleTickets st=new SaleTickets();
//四个窗口
Thread t1=new Thread(st,"窗口1");
Thread t2=new Thread(st,"窗口2");
Thread t3=new Thread(st,"窗口3");
Thread t4=new Thread(st,"窗口4");
t1.start();
t2.start();
t3.start();
t4.start();
}
}
运行结果如下:
二,生产者和消费者
就相当于模拟一个流水线工作,比如有:洗碗的,碗柜,和烘干碗的
它们三个协调工作,碗柜上有6个放碗的槽,洗碗后把碗放到碗柜上,然后从碗柜上拿完烘干。需要确保不能给碗柜上放碗超过6个,不能在碗柜上没碗的时候还拿碗烘干。
代码如下:
import java.util.Arrays;
//制作一个碗架
class Shelf{
private String []str={"O","O","O","O","O","O"};//6个槽
int i;//定义碗
public void put(){//放碗
synchronized (this) {
if(this.isFull()){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
str[i++]="碗";
System.out.println(this);
this.notify();//只要没取空,取碗的就应该醒着
}
}
//****************************************************************************
public void get(){//取碗
synchronized (this) {
if(this.isEmpty()){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
str[--i]="O";
System.out.println(this);
this.notify();//只要没放满,放碗的就应该醒着
}
}
//***************************************************************************
public boolean isFull(){//表示放满了碗
return i==6;
}
//***************************************************************************
public boolean isEmpty(){//表示取空了
return i==0;
}
//***************************************************************************
public String toString() {
return Arrays.toString(str);
}
}
//******************************************************************************
//******************************************************************************
class FF implements Runnable{ //线程放碗
private Shelf s;
public FF(Shelf s){
this.s=s;
}
public void run(){
//只管取碗
while(true){
s.get();
}
}
}
//********************************************************************
// ********************************************************************
class QQ implements Runnable{
private Shelf s;//关联碗柜
public QQ(Shelf s){
this.s=s;
}
@Override
public void run() {
//只管放碗
while(true){
s.put();
}
}
}
//***************************************************************
//***************************************************************
public class Test {
public static void main(String[] args) {
Shelf s=new Shelf();
QQ q=new QQ(s);
FF f=new FF(s);
Thread t1=new Thread(q);
Thread t2=new Thread(f);
t1.start();
t2.start();
}
}