模拟4个线程同时卖100张票的问题上,个人认为可以使用try方法,先睡眠后锁定的方式,让进程都进来更好- public class Ticket implements Runnable {
- private int num = 1;
- private String name;
-
- public Ticket(String name){
- this.name = name;
- }
-
- @Override
- public void run() {
-
- while(num <= 100){
- //先睡眠,后锁定,让四个都进程进来
- try{
- Thread.sleep(1000); //睡眠
- }catch(InterruptedException e){
- e.printStackTrace();
- }
- synchronized(this){ //锁定
- if(num<=100)
- System.out.println(name + Thread.currentThread().getName() + "...sale...第" + num + "张票" );
- num = num +1;
- }
-
- }
- }
- }
复制代码
|