需求:
三个窗口同时卖票,用实现Runnable方式
public class T_Card implements Runnable{//也可继承Thread
static int currCard=50;
static Object obj=new Object();
@Override
public void run() {
while (true){
try {
Thread.sleep(1000);//使当前执行的线程休眠(暂停执行)用于指定的毫秒数
synchronized (obj){
if (currCard>0){
System.out.println("线程编号:"+Thread.currentThread().getName()+" "+"卖出的票是:"+currCard);
currCard--;
}else {
System.out.println("该车次的票已售完......");
System.exit(0);
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
T_Card tc1=new T_Card();
Thread t1=new Thread(tc1);
t1.start();//开启线程1
T_Card tc2=new T_Card();
Thread t2=new Thread(tc2);
t2.start();//开启线程2
T_Card tc3=new T_Card();
Thread t3=new Thread(tc3);
t3.start();//开启线程3
}
执行结果:
线程编号:Thread-2 卖出的票是:20
线程编号:Thread-1 卖出的票是:19
线程编号:Thread-0 卖出的票是:18
线程编号:Thread-1 卖出的票是:17
线程编号:Thread-0 卖出的票是:16
线程编号:Thread-2 卖出的票是:15
线程编号:Thread-1 卖出的票是:14
线程编号:Thread-2 卖出的票是:13
线程编号:Thread-0 卖出的票是:12
线程编号:Thread-1 卖出的票是:11
线程编号:Thread-0 卖出的票是:10
线程编号:Thread-2 卖出的票是:9
线程编号:Thread-1 卖出的票是:8
线程编号:Thread-2 卖出的票是:7
线程编号:Thread-0 卖出的票是:6
线程编号:Thread-1 卖出的票是:5
线程编号:Thread-0 卖出的票是:4
线程编号:Thread-2 卖出的票是:3
线程编号:Thread-1 卖出的票是:2
线程编号:Thread-2 卖出的票是:1
该车次的票已售完......
Process finished with exit code 0