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{
@Override
public 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{
@Override
public 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);
}
}
}
}