1、线程礼让
(1)礼让线程,让当前正在执行的线程暂停,但不阻塞
(2)将线程从运行状态转为就绪状态
(3)让cpu重新调度,礼让不一定成功!看cpu心情
package state;
//测试礼让线程
//礼让不一定成功,看cpu心情
public class TestYield {public static void main(String[] args) {MyYield myYield = new MyYield();new Thread(myYield,"a").start();new Thread(myYield,"b").start();
}
}
class MyYield implements Runnable{
@Overridepublic void run() {System.out.println(Thread.currentThread().getName()+"线程开始执行");Thread.yield();//礼让System.out.println(Thread.currentThread().getName()+"线程停止执行");}
}
线程礼让成功
线程礼让失败
2、线程强制执行
package state;
//测试Join方法 想象为插队
public class TestJoin implements Runnable{@Overridepublic void run() {for (int i = 0; i < 1000; i++) {System.out.println("线程VIP来了"+i);}}
public static void main(String[] args) {TestJoin testJoin = new TestJoin();new Thread(testJoin).start();
//主线程for (int i = 0; i < 1000; i++) {if (i==200){try {new Thread(testJoin).join();} catch (InterruptedException e) {throw new RuntimeException(e);}}System.out.println("主线程"+i);}}
}
3、线程状态观测
package state;
//观察测试线程的状态
public class TestState {public static void main(String[] args) {//lambda表达式Thread thread = new Thread(()->{for (int i = 0; i < 5; i++) {try {Thread.sleep(1000);} catch (InterruptedException e) {throw new RuntimeException(e);}}System.out.println("///");});
//观察状态Thread.State state = thread.getState();System.out.println(state);//New//观察启动后thread.start();//启动线程state = thread.getState();System.out.println(state);
while (state!=Thread.State.TERMINATED){//只要线程不终止,就一直输出状态try {Thread.sleep(100);state = thread.getState();//更新线程状态System.out.println(state);//输出状态} catch (InterruptedException e) {throw new RuntimeException(e);}}}
}