`
阿尔萨斯
  • 浏览: 4179904 次
社区版块
存档分类
最新评论

Java Thread类的 yield()、join()

 
阅读更多

yield:

解释它之前,先简述下,多线程的执行流程:多个线程并发请求执行时,由cpu决定优先执行哪一个,即使通过thread.setPriority(),设置了

线程的优先级,也不一定就是每次都先执行它

yield,表示暂停当前线程,执行其他线程(包括自身线程) 由cpu决定

public class TestYield implements Runnable {

	public void run() {
		for (int i = 1; i <= 15; i++) {
			System.out.println(Thread.currentThread().getName() + ": " + i);
			// 暂停当前正在执行的线程对象,并执行其他线程,就是进入就绪状态
			Thread.currentThread().yield();
			// 可能还会执行 本线程,
		}
	}

	public static void main(String[] args) {
		TestYield runn = new TestYield();
		Thread t1 = new Thread(runn);
		Thread t2 = new Thread(runn);
		Thread t3 = new Thread(runn);
		
		t2.setPriority(t2.getPriority()+1);
		t1.start();
		t2.start();
		t3.start();

	}
}

join:

阻塞所在线程,等调用它的线程执行完毕,再向下执行

	public static void main(String[] args) throws InterruptedException {

		final Thread thread1 = new Thread() {
			public void run() {
				System.out.println("我是第一个");
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				System.out.println("我虽然睡了一会,但我是第二个");
			};
		};
		thread1.start();
//		thread1.join();		在这阻塞主线程
		Thread thread2 = new Thread() {
			public void run() {
				try {
					thread1.join();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}// 等待t1线程 执行完结,才继续向下执行	在这阻塞子线程
				System.out.println("我是第三个");
			};
		};
		thread2.start();
	}


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics