mysterin / question_and_answer

1 stars 0 forks source link

线程阻塞和等待 #150

Closed mysterin closed 5 years ago

mysterin commented 5 years ago

阻塞

当一个线程试图获取锁, 这个锁被其他线程持有, 当前线程就进入阻塞. 示例: blocking-thread线程会进入阻塞.

@Test
public void blocking() {
    Object obj = new Object();
    Thread thread = new Thread(()->{
        try {
            Thread.sleep(1000);
            synchronized (obj) {
                System.out.println("thread...sync");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }, "blocking-thread");
    thread.start();
    synchronized (obj) {
        while (true);
    }
}

等待

当前线程等待其他线程发来通知, 收到通知后可能会继续执行, 也有可能去获取锁进入阻塞. 比如Object.wait(), Thread.join(), 示例: waiting-thread线程会进入等待.

@Test
public void waiting() throws InterruptedException {
    Object obj = new Object();
    Thread thread = new Thread(() -> {
        synchronized (obj) {
            System.out.println("waiting-thread");
            try {
                obj.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }, "waiting-thread");
    thread.start();
    Thread.sleep(1000);
    synchronized (obj) {
        while (true);
    }
}