一、Thread的start() 及 run()
- start()方法来启动线程,真正实现了多线程运行,这时无需等待run方法体代码执行完毕而直接继续执行下面的代码
- run()方法当作普通方法的方式调用,程序还是要顺序执行,还是要等待run方法体执行完毕后才可继续执行下面的代码(在主线程中执行的run())
Thread thread1 = new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("输出:" + "thread1执行");
}
});
Thread thread2 = new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(400);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("输出:" + "thread2执行");
}
});
Thread thread3 = new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("输出:" + "thread3执行");
}
});
thread1.start();
thread2.start();
thread3.start();
// 输出:thread3执行
// 输出:thread2执行
// 输出:thread1执行
thread1.run();
thread2.run();
thread3.run();
// 输出:thread1执行(在主线程中执行)
// 输出:thread2执行(在主线程中执行)
// 输出:thread3执行(在主线程中执行)
二、join()
2.1 作用:让主线程阻塞,直到子线程结束之后才能继续运行
2.2、使用:
//使用上面的三个Thread
thread1.start();
thread1.join();
thread2.start();
thread2.join();
thread3.start();
thread3.join();
// 输出:thread1执行
// 输出:thread2执行
// 输出:thread3执行
thread1.start();
thread1.join(10);//最多阻塞10毫秒
thread2.start();
thread2.join(10);
thread3.start();
thread3.join(10);
// 输出:thread3执行
// 输出:thread2执行
// 输出:thread1执行
2.3、分析
- thread1启动,主线程调用thread1的join()方法,thread1存活?阻塞0毫秒:join()执行结束,主线程执行thread2.start();
- thread1启动,主线程调用thread1的join(10)方法,死循环开始,thread1正在执行,主线程阻塞10,循环继续,时间delay《=0,循环结束
源码
/**
* 对象锁,thread类的锁
* @param millis 最长阻塞多久
*/
public final synchronized void join(long millis)
throws InterruptedException {
//jion动作开始时间
long base = System.currentTimeMillis();
//过了多久
long now = 0;
if (millis < 0) {
throw new IllegalArgumentException("timeout value is negative");
}
//join()默认0 millis
if (millis == 0) {
//这个thread正在运行,native方法
while (isAlive()) {
//thread类的锁,调用线程阻塞
wait(0);
}
} else {
while (isAlive()) {
long delay = millis - now;
if (delay <= 0) {
break;
}
//阻塞最长时间delay
wait(delay);
now = System.currentTimeMillis() - base;
}
}
}