Java面试题-输出*Thread-0#Thread-1@Thread-2

class MyThread implements Runnable{
    private static int i = 3;
    private static int divnumber = 6;
    private static int Count = 0;
    @Override
    public void run() {
        while(Count < 21) {
            synchronized (this) {//二重加锁
                if(Count >= 21){
                    return;
                }
                if ("Thread-0".equals(Thread.currentThread().getName()) && Count%3 == 0) {
                    System.out.print("*" + Thread.currentThread().getName());
                    Count++;
                } else if ("Thread-1".equals(Thread.currentThread().getName()) && Count%3 == 1) {
                    System.out.print("#" + Thread.currentThread().getName());
                    Count++;
                } else if ("Thread-2".equals(Thread.currentThread().getName()) && Count%3 == 2){
                    System.out.print("@" + Thread.currentThread().getName());
                    Count++;
                }
                if (Count % i == 0) {
                    System.out.println();
                    i+=divnumber;
                    divnumber+=3;
                }
            }
        }
    }
}

public class Main {
    public static void main(String[] args){
        Runnable runnable = new MyThread();
        new Thread(runnable).start();
        new Thread(runnable).start();
        new Thread(runnable).start();
    }
}

猜你喜欢

转载自blog.csdn.net/qq_38449518/article/details/80244134
今日推荐