多个窗口同时卖票 用实现Runnable方式
我们以三个窗口卖票为例
先创建一个类,声明两个静态全局变量
30表示票数
static int num = 30;
static Integer in = new Integer(1);
用此类实现Runnable接口
实现run()方法
为防止数据重复,使用同步synchronized
@Override
public void run() {
while (true){
synchronized (in){
if(num>0){
System.out.println(num+"已卖出");
num--;
}else {
System.exit(0);
}
}
}
}
创建main()方法
类实现Runnable接口,不能直接调用start()方法
通过Thread类的构造方法,声明三个线程
分别调用start()方法
public static void main(String[] args) {
Thread t1=new Thread(new Demo2());
t1.start();
Thread t2=new Thread(new Demo2());
t2.start();
Thread t3=new Thread(new Demo2());
t3.start();
}
执行结果: