两个线程一次打印数字

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();
    }
}

猜你喜欢

转载自panpan-xin.iteye.com/blog/2376432