java多线程(10)—顺序打印ABC

越努力越幸运!

 java多线程面试题

public class Test {
 
    public static void main(String[] args) {
        Thread a = new Thread(new Task("A",0));
        Thread b = new Thread(new Task("B",1));
        Thread c = new Thread(new Task("C",2));
        a.start();
        b.start();
        c.start();
    }
     
    static class Task implements Runnable{
         
        private String one;
        private int count;
        private static int num = 0;
         
        public Task(String one,int count){
            this.one = one;
            this.count = count;
        }
         
        @Override
        public void run() {
             
            int i = 0;
            while(i < 10){
                synchronized(Task.class){
                    if(num % 3 == count){
                        num++;
                        System.out.println(one);
                    }else{
                        continue;
                    }
                }
                i++;
            }
        }
    }
}

 lock实现

猜你喜欢

转载自blog.csdn.net/hezuo1181/article/details/82948586