Java 线程切换

@ 线程暂停唤醒和切换

public class ThreadSleepAndWait {
class Run1 implements Runnable {

    @Override
    public void run() {
        synchronized (ThreadSleepAndWait.class) {
            System.out.println("Run1 start");
            try {
                ThreadSleepAndWait.class.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Run1 is going on ....");
        }
    }
}

class Run2 implements Runnable {
    @Override
    public void run() {
        synchronized (ThreadSleepAndWait.class) {
            System.out.println("Run2 start");
            ThreadSleepAndWait.class.notify();
            System.out.println("Run2 is going on ....");
        }
    }
}

@Test
public void test() {
    new Thread(new Run1()).start();
    new Thread(new Run2()).start();
}}

ThreadSleepAndWait.class.wait();当前线程挂起
此时执行线程2
ThreadSleepAndWait.class.notify();唤起线程1,线程1重新进入等待队列
上面的执行结果是:
Run1 start
Run2 start
Run2 is going on …
Run1 is going on …

猜你喜欢

转载自blog.csdn.net/w517272812/article/details/88567254
今日推荐