package cn.itcast2;
/*
* 线程安全问题:
* 多个窗口卖指定个数的票
* 3个窗口卖100张票
* 票:共享数据
* 窗口:线程
*/
public class Ticket implements Runnable{
//定义成员变量,来表示车票的个数
private int tickedNumber = 100;
//定义一个对象,来做代码块同步的锁
private Object object = new Object();
//重写run方法
@Override
public void run() {
//同步代码块
synchronized(object){
//来确定条件
while(true){
if(tickedNumber>0){
try {//休眠防止一张票买多次
Thread.sleep(10L);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"正在售票:"+tickedNumber--);//卖出一张,票数减一
}
}
}
}
}
package cn.itcast2;
public class Test3 {
public static void main(String[] args) {
//创建票对象
Ticket ticket = new Ticket();
//创建线程对象
Thread thread = new Thread(ticket,"窗口1");
Thread thread2= new Thread(ticket,"窗口2");
Thread thread3= new Thread(ticket,"窗口3");
//开启线程
thread.start();
thread2.start();
thread3.start();
}
}
|
|