学习线程的过程中,肯定会遇到卖票问题,假设有三个窗口要卖2000张票,程序正确实现这个问题,我们要考虑几个问题:一,怎么实现多个窗口共享一个资源;二,在售票过程中怎么保持各线程的原子性,防止两个窗口同时出售一张票的情况。我们看以下代码
/*
* 功能:卖票
*/
package demo06;
public class Demo06 {
public static void main(String[] args) {
// TODO Auto-generated method stub
TicketWindow tw1=new TicketWindow();
Thread t1=new Thread(tw1);
Thread t2=new Thread(tw1);
Thread t3=new Thread(tw1);
t1.start();
t2.start();
t3.start();
}
}
//售票窗口类
class TicketWindow implements Runnable{
//一共两千张
private int num=2000;
public void run(){
while(true){
//出票速度一秒一张
try{
Thread.sleep(1000);
}catch(Exception e){
e.printStackTrace();
}
//认为if else 要保证原子性(同步代码块)
synchronized(this)
{
//先判断是否还有票
if (num>0)
{
//Thread.currentThread().getName()显示当前线程名
System.out.println(Thread.currentThread().getName()+"在售出第"+num+"票");
num--;
}
else {
break;
}
}
}
}
}
在这里,我们用Thread实例多个对象,利用各个对象实现多窗口售票。这里的synchronized来实现一个代码块的原子性。