| 
| 复制代码
//public class Temp {
//        public static void main(String[] args) {
//                
//        }
//}
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Temp {
        public static void main(String[] args) {
                Ticket t = new Ticket(100);
                for(int i=0; i<5; i++){
                        new Thread(t,"窗口"+i).start();
                        try{
                                Thread.sleep(200);
                        }catch(InterruptedException e){
                                e.printStackTrace();
                        }
//                        t.flag = false;//设为flase会导致只有第一个线程能进入if(flag),后面的线程无法运行,如图所示
                }
        }
}
class Ticket implements Runnable{
        private int num;
        private String id;
        boolean flag = true;
        Lock lock = new ReentrantLock();
        Condition con = lock.newCondition();
        public Ticket(int num){
                this.num = num;
        }
        public int getNum(){
                return num;
        }
        public void run(){
//                lock.lock();
                if(flag){
                        while(true){
                                synchronized(this){
                                        if(num > 0){
                                                try{
                                                        Thread.sleep(20);
                                                        System.out.println(Thread.currentThread().getName()+"----"+num--);
                                                }catch(InterruptedException e){
                                                        e.printStackTrace();
                                                }
//                                                lock.unlock();
                                                this.notifyAll();
//                                                break; //break会当前进程
                                        }
                                        else{
//                                                lock.unlock();
                                                break;
                                        }
                                }
                        }
                }
        }
}
 | 
 
1.png
(2.82 KB, 下载次数: 140)
 
 
2.png
(3.46 KB, 下载次数: 144)
 
 |