Thread.yield()方法表示交出主动权,join表示等待当前线程,可以指定秒数
Thread.yield()方法表示交出主动权,join表示等待当前线程,可以指定秒数
学习了:http://www.importnew.com/14958.html 膜拜一下
源码膜拜:
Thread.yield()没准,顺序输出不一定;
package com.stono.thread; public class YieldExample { public static void main(String[] args) { Thread producer = new Producer(); Thread consumer = new Consumer(); producer.setPriority(Thread.MIN_PRIORITY); consumer.setPriority(Thread.MAX_PRIORITY); producer.start(); consumer.start(); } } class Producer extends Thread{ @Override public void run() { for(int i=0;i<5;i++){ System.out.println("I am Producer: Procuded Item ============="+ i); Thread.yield(); } } } class Consumer extends Thread{ @Override public void run() { for(int i=0;i<5;i++){ System.out.println("I am consumer: Consumed Item "+i); Thread.yield(); } } }
Join表示要等待当前线程,可以指定等待的毫秒数;
package com.stono.thread; import java.util.concurrent.TimeUnit; public class JoinExample { public static void main(String[] args) throws InterruptedException { Thread t = new Thread(new Runnable() { public void run() { System.out.println("First task started"); System.out.println("Sleeping for 2 seconds"); try { //Thread.sleep(2000); TimeUnit.SECONDS.sleep(2); } catch (Exception e) { e.printStackTrace(); } System.out.println("First task complete"); } }); Thread t1 = new Thread(new Runnable() { public void run() { System.out.println("Second task completed"); } }); t.start(); t.join(); // t.join(100); // 这个表示等待100毫秒 t1.start(); } }