一 Java多线程-线程生命周期( 二 )


1.2、T1被唤醒后等待启动,T2继续执行,T2执行完,T1获得CPU后继续执行
2、T2先执行
2.1、T2执行完,T1启动,让出CPU,由于没有线程再来执行notify,程序无限期等待
这里要强调的重点是:

1、wait会让出CPU而notify不会
2、wait重点在通知其它同用一个object的线程“我暂时不用了”,并且让出CPU
3、notify重点在于通知使用object的对象“我用完了!”
如果说只有两个线程的时候,还能尝试着分析一下结果,那么当有四个线程的时候会如何呢?看看代码:
public static void main(String[] args) {Thread t1 = new Thread(new Runnable() {@Overridepublic void run() {synchronized ("锁") {System.out.println("t1 start");try {// t1释放锁"锁".wait();} catch (InterruptedException e) {e.printStackTrace();}System.out.println("t1 end");}}});Thread t2 = new Thread(new Runnable() {@Overridepublic void run() {synchronized ("锁") {try {System.out.println("t2 start");// 随机通知一个等待的线程进入等待队列"锁".notify();System.out.println("t2 end");} catch (Exception e) {e.printStackTrace();}}}});Thread t3 = new Thread(new Runnable() {@Overridepublic void run() {synchronized ("锁") {try {System.out.println("t3 start");// 随机通知一个等待的线程进入等待队列"锁".notify();System.out.println("t3 end");} catch (Exception e) {e.printStackTrace();}}}});Thread t4 = new Thread(new Runnable() {@Overridepublic void run() {synchronized ("锁") {try {System.out.println("t4 start");// t4释放锁"锁".wait();System.out.println("t4 end");} catch (Exception e) {e.printStackTrace();}}}});t1.start();t2.start();t3.start();t4.start();}然后同时开启这四个线程,但结果是无法预料!为什么?因为只有两种可能的流程(要么wait先执行完,要么notify先执行完),至于每种流程里面怎么执行的?不知道!不清楚!无法预料!这就是多线程让人困惑的地方和魅力所在 。
而且线程还有一个无赖的行为就是:虽然你有优先级,但我不保证有用!
public class MyThread extends Thread {MyThread(String s) {super(s);}@Overridepublic void run() {for (int i = 0; i <= 10; i++) {System.out.println(getName() + " : " + i);if (i == 5) {Thread.yield();}}}public static void main(String[] args) throws InterruptedException {System.out.println("主线程启动");Thread t1 = new MyThread("t1");Thread t2 = new MyThread("t2");t1.setPriority(Thread.MIN_PRIORITY);t1.start();t2.setPriority(Thread.MAX_PRIORITY);t2.start();t1.join();t2.join();System.out.println("主线程结束");}}这里不管怎么设置t1或者t2的优先级,都没有用,运行的结果每次都可能不一样 。
线程的生命周期6类5法算是比较简单的,是基础中的基础 。但是用好很难,关键在于多练多想,多多尝试各种组合 。
【一 Java多线程-线程生命周期】

经验总结扩展阅读