兩個線程一次打印數字

public class Test {
    private static boolean flag = true;
    private static final Object LOCK = new Object();
    private static int i=0;
    public static void print(String name){
        i++;
        System.out.println(name+"------"+i);
    }
    public static void main(String[] args) {
        // 兩個線程 交替打印字符串
        Thread a = new Thread() {
            public void run() {
                while (i < 100)
                    synchronized (LOCK) {
                        {
                            if (false == flag) {
                                try {
                                    LOCK.wait();// 在wait後的瞬間線程b得到鎖
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }
                            flag = false;
                            print(getName());
                            LOCK.notify();// 在這裏雖然喚醒了另一個線程b,但鎖並沒有釋放
                        }
                    }
            };
        };
        Thread b = new Thread() {
            public void run() {
                while (1<100)
                    synchronized (LOCK) {
                        {
                            if (true == flag) {
                                try {
                                    LOCK.wait();// 在wait後的瞬間線程b得到鎖
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }
                            flag = true;
                            print(getName());
                            LOCK.notify();// 在這裏雖然喚醒了另一個線程b,但鎖並沒有釋放
                        }
                    }
            };
        };
        a.start();
        b.start();
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章