窗口取号系统

1 第一个版本,有bug

public class  Demo {
    
    public static void main(String[] args) {
        
        Runnable runnable = new WindowRunnable();
        
        new Thread(runnable,"窗口1").start();
        new Thread(runnable,"窗口2").start();
        new Thread(runnable,"窗口3").start();
        
    }
    
    
    static class   WindowRunnable implements Runnable {
        
        int index = 0;
        static final int MAX = 50;
        
        @Override
        public  void  run() {
            
            while(index < MAX) {
                printMsg();
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            
        }
        
        public synchronized void printMsg(){
            System.out.println(Thread.currentThread().getName()+ ": "+ (++index));
        }
        
    }

}

当index为49时,同时有两个线程进入方法了,一个拿到锁了,去执行,一个没有得到锁,就等待别的线程执行完再执行,这时候index已经为50了,再加一次变成51

猜你喜欢

转载自www.cnblogs.com/moris5013/p/10695055.html