public class TestYield { public static void main(String[] args) { new Thread(new MyYield1(), "A").start(); new Thread(new MyYield2(), "B").start(); } } class MyYield1 implements Runnable { @Override public void run() { System.out.println("开始A"); Thread.yield();// 暂停,让cpu重新调度 System.out.println("结束A"); } } class MyYield2 implements Runnable { @Override public void run() { System.out.println("开始B"); System.out.println("结束B"); } }
public class JoinTest { public static void main(String[] args) { Thread thread = new Thread(new MyJoin(),"a"); thread.start(); // 线程启动 for (int i = 0; i < 10; i++) { System.out.println(Thread.currentThread().getName()+"--> 第" +i); if (i == 5){// main线程中断,a线程介入 try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } } } } } class MyJoin implements Runnable{ @Override public void run() { for (int i = 0; i < 10; i++) { System.out.println(Thread.currentThread().getName()+"-->Join, 第"+i); } } }
执行结果如图: