【69期】面试官:对并发熟悉吗?谈谈线程间的协作(wait/notify/sleep/yield/join)
阅读本文大概需要 8.5 分钟。
来自:www.cnblogs.com/paddix/p/5381958.html
一、线程的状态
New:新建状态,当线程创建完成时为新建状态,即new Thread(…),还没有调用start方法时,线程处于新建状态。
Runnable:就绪状态,当调用线程的的start方法后,线程进入就绪状态,等待CPU资源。处于就绪状态的线程由Java运行时系统的线程调度程序(thread scheduler)来调度。
Running:运行状态,就绪状态的线程获取到CPU执行权以后进入运行状态,开始执行run方法。
Blocked:阻塞状态,线程没有执行完,由于某种原因(如,I/O操作等)让出CPU执行权,自身进入阻塞状态。
Dead:死亡状态,线程执行完成或者执行过程中出现异常,线程就会进入死亡状态。

二、wait/notify/notifyAll方法的使用
1、wait方法:

wait()方法的作用是将当前运行的线程挂起(即让其进入阻塞状态),直到notify或notifyAll方法来唤醒线程.
wait(long timeout),该方法与wait()方法类似,唯一的区别就是在指定时间内,如果没有notify或notifAll方法的唤醒,也会自动唤醒。
至于wait(long timeout,long nanos),本意在于更精确的控制调度时间,不过从目前版本来看,该方法貌似没有完整的实现该功能,其源码(JDK1.8)如下:
public final void wait(long timeout, int nanos) throws InterruptedException {
if (timeout < 0) {
throw new IllegalArgumentException("timeout value is negative");
}
if (nanos < 0 || nanos > 999999) {
throw new IllegalArgumentException(
"nanosecond timeout value out of range");
}
if (nanos >= 500000 || (nanos != 0 && timeout == 0)) {
timeout++;
}
wait(timeout);
}
package com.paddx.test.concurrent;
public class WaitTest {
public void testWait(){
System.out.println("Start-----");
try {
wait(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("End-------");
}
public static void main(String[] args) {
final WaitTest test = new WaitTest();
new Thread(new Runnable() {
@Override
public void run() {
test.testWait();
}
}).start();
}
}
Start-----
Exception in thread "Thread-0" java.lang.IllegalMonitorStateException
at java.lang.Object.wait(Native Method)
at com.paddx.test.concurrent.WaitTest.testWait(WaitTest.java:8)
at com.paddx.test.concurrent.WaitTest$1.run(WaitTest.java:20)
at java.lang.Thread.run(Thread.java:745)
Thrown to indicate that a thread has attempted to wait on an object's monitor or to notify other threads waiting on an object's monitor without owning the specified monitor.
package com.paddx.test.concurrent;
public class WaitTest {
public synchronized void testWait(){//增加Synchronized关键字
System.out.println("Start-----");
try {
wait(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("End-------");
}
public static void main(String[] args) {
final WaitTest test = new WaitTest();
new Thread(new Runnable() {
@Override
public void run() {
test.testWait();
}
}).start();
}
}
Start-----
End-------
2、notify/notifyAll方法

package com.paddx.test.concurrent;
public class NotifyTest {
public synchronized void testWait(){
System.out.println(Thread.currentThread().getName() +" Start-----");
try {
wait(0);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() +" End-------");
}
public static void main(String[] args) throws InterruptedException {
final NotifyTest test = new NotifyTest();
for(int i=0;i<5;i++) {
new Thread(new Runnable() {
@Override
public void run() {
test.testWait();
}
}).start();
}
synchronized (test) {
test.notify();
}
Thread.sleep(3000);
System.out.println("-----------分割线-------------");
synchronized (test) {
test.notifyAll();
}
}
}
Thread-0 Start-----
Thread-1 Start-----
Thread-2 Start-----
Thread-3 Start-----
Thread-4 Start-----
Thread-0 End-------
-----------分割线-------------
Thread-4 End-------
Thread-3 End-------
Thread-2 End-------
Thread-1 End-------
线程需要被唤醒(超时唤醒或调用notify/notifyll)。
线程唤醒后需要竞争到锁(monitor)。
三、sleep/yield/join方法解析
1、sleep
package com.paddx.test.concurrent;
public class SleepTest {
public synchronized void sleepMethod(){
System.out.println("Sleep start-----");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Sleep end-----");
}
public synchronized void waitMethod(){
System.out.println("Wait start-----");
synchronized (this){
try {
wait(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Wait end-----");
}
public static void main(String[] args) {
final SleepTest test1 = new SleepTest();
for(int i = 0;i<3;i++){
new Thread(new Runnable() {
@Override
public void run() {
test1.sleepMethod();
}
}).start();
}
try {
Thread.sleep(10000);//暂停十秒,等上面程序执行完成
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("-----分割线-----");
final SleepTest test2 = new SleepTest();
for(int i = 0;i<3;i++){
new Thread(new Runnable() {
@Override
public void run() {
test2.waitMethod();
}
}).start();
}
}
}
Sleep start-----
Sleep end-----
Sleep start-----
Sleep end-----
Sleep start-----
Sleep end-----
-----分割线-----
Wait start-----
Wait start-----
Wait start-----
Wait end-----
Wait end-----
Wait end-----
2、yield方法
package com.paddx.test.concurrent;
public class YieldTest implements Runnable {
@Override
public void run() {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
for(int i=0;i<5;i++){
System.out.println(Thread.currentThread().getName() + ": " + i);
Thread.yield();
}
}
public static void main(String[] args) {
YieldTest runn = new YieldTest();
Thread t1 = new Thread(runn,"FirstThread");
Thread t2 = new Thread(runn,"SecondThread");
t1.start();
t2.start();
}
}
FirstThread: 0
SecondThread: 0
FirstThread: 1
SecondThread: 1
FirstThread: 2
SecondThread: 2
FirstThread: 3
SecondThread: 3
FirstThread: 4
SecondThread: 4
/**
* A hint to the scheduler that the current thread is willing to yield
* its current use of a processor. The scheduler is free to ignore this
* hint.
*
*Yield is a heuristic attempt to improve relative progression
* between threads that would otherwise over-utilise a CPU. Its use
* should be combined with detailed profiling and benchmarking to
* ensure that it actually has the desired effect.
*
*It is rarely appropriate to use this method. It may be useful
* for debugging or testing purposes, where it may help to reproduce
* bugs due to race conditions. It may also be useful when designing
* concurrency control constructs such as the ones in the
* {@link java.util.concurrent.locks} package.
*/
调度器可能会忽略该方法。
使用的时候要仔细分析和测试,确保能达到预期的效果。
很少有场景要用到该方法,主要使用的地方是调试和测试。
3、join方法

public final void join() throws InterruptedException {
join(0);
}
public final synchronized void join(long millis)
throws InterruptedException {
long base = System.currentTimeMillis();
long now = 0;
if (millis < 0) {
throw new IllegalArgumentException("timeout value is negative");
}
if (millis == 0) {
while (isAlive()) {
wait(0);
}
} else {
while (isAlive()) {
long delay = millis - now;
if (delay <= 0) {
break;
}
wait(delay);
now = System.currentTimeMillis() - base;
}
}
}
public final synchronized void join(long millis, int nanos)
throws InterruptedException {
if (millis < 0) {
throw new IllegalArgumentException("timeout value is negative");
}
if (nanos < 0 || nanos > 999999) {
throw new IllegalArgumentException(
"nanosecond timeout value out of range");
}
if (nanos >= 500000 || (nanos != 0 && millis == 0)) {
millis++;
}
join(millis);
}
package com.paddx.test.concurrent;
public class JoinTest implements Runnable{
@Override
public void run() {
try {
System.out.println(Thread.currentThread().getName() + " start-----");
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName() + " end------");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
for (int i=0;i<5;i++) {
Thread test = new Thread(new JoinTest());
test.start();
}
System.out.println("Finished~~~");
}
}
Thread-0 start-----
Thread-1 start-----
Thread-2 start-----
Thread-3 start-----
Finished~~~
Thread-4 start-----
Thread-2 end------
Thread-4 end------
Thread-1 end------
Thread-0 end------
Thread-3 end------
package com.paddx.test.concurrent;
public class JoinTest implements Runnable{
@Override
public void run() {
try {
System.out.println(Thread.currentThread().getName() + " start-----");
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName() + " end------");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
for (int i=0;i<5;i++) {
Thread test = new Thread(new JoinTest());
test.start();
try {
test.join(); //调用join方法
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Finished~~~");
}
}
Thread-0 start-----
Thread-0 end------
Thread-1 start-----
Thread-1 end------
Thread-2 start-----
Thread-2 end------
Thread-3 start-----
Thread-3 end------
Thread-4 start-----
Thread-4 end------
Finished~~~
四、总结
推荐阅读:
【68期】面试官:对并发熟悉吗?说说Synchronized及实现原理
【67期】谈谈ConcurrentHashMap是如何保证线程安全的?
微信扫描二维码,关注我的公众号
朕已阅 

