Java多线程系列(七)wait,notify实现两个线程的交替执行

代码一:

Thread thread1;
Thread thread2;
thread1 = new Thread(new Runnable() {
    @Override
    public void run() {
        while (true) {
            synchronized (lock1) {
                Log.i(TAG, "进入thread1\"......开始休眠\"");
                try {
                    Thread.sleep(5000);
                    lock1.notify();
                    lock1.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
});

thread1.start();
thread2 = new Thread(new Runnable() {
    @Override
    public void run() {
        while (true) {
            synchronized (lock1) {
                Log.i(TAG, "进入thread2......开始休眠");
                try {
                    Thread.sleep(5000);
                    lock1.notify();
                    lock1.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
});
thread2.start();

 

代码二:

public static void main(String[] args) {
    Thread t1 = new Thread(demo2::print1);
    Thread t2 = new Thread(demo2::print2);

    t1.start();
    t2.start();
}

public synchronized void print2() {
    for (int i = 1; i <= 100; i += 2) {
        System.out.println(i);
        this.notify();
        try {
            this.wait();
            Thread.sleep(100);// 防止打印速度过快导致混乱
        } catch (InterruptedException e) {
            // NO
        }
    }
}

public synchronized void print1() {
    for (int i = 0; i <= 100; i += 2) {
        System.out.println(i);
        this.notify();
        try {
            this.wait();
            Thread.sleep(100);// 防止打印速度过快导致混乱
        } catch (InterruptedException e) {
            // NO
        }
    }
}

 

 

关键点:

(一),先notify使其他线程处于活跃状态

(二),wait释放锁

你可能感兴趣的:(安卓)