1 . sleep() 在睡眠的時候 會釋放cpu 讓給其他線程執行, 即使沒有其他線程 搶占cpu 也需要等待睡眠時間到了以后才能真正的指定. package com.qf.demo3; public class Test2 { public static void main(String[] args) { MyThread2 thread2 = new MyThread2(); MyThead3 thead3 = new MyThead3(); thread2.start(); thead3.start(); } } class MyThread2 extends Thread{ @Override public void run() { for (int i = 0; i < 20; i++) { try { if(i>5){ Thread.sleep(1000);// 可以讓線程 睡眠 指定的毫秒數 // 在睡眠的時候 會釋放cpu 讓給其他線程執行 // 即使沒有其他線程 搶占cpu 也需要等待睡眠時間到了以后才能真正的指定 } } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"--->"+i); } } } class MyThead3 extends Thread{ @Override public void run() { for (int i = 0; i < 100; i++) { System.out.println("二狗跑了"+i+"圈"); } } } 2 . yield(); 執行的時候 會 讓出cpu , 但是 會立馬同其他的線程搶占 cpu package com.qf.demo3; public class Test3 { public static void main(String[] args) { MyThrad4 myThrad4 = new MyThrad4("白志凱"); MyThead5 myThead5 = new MyThead5(); myThrad4.start(); myThead5.start(); } } class MyThrad4 extends Thread{ public MyThrad4(String name) { super(name); } @Override public void run() { for (int i = 0; i < 20; i++) { Thread.yield();// 執行的時候 會 讓出cpu , 但是 會立馬同其他的線程搶占 cpu System.out.println(Thread.currentThread().getName()+"跑了"+i+"圈"); } } } class MyThead5 extends Thread{ @Override public void run() { for (int i = 0; i < 20; i++) { System.out.println("不傻的跑了"+i+"圈"); } } } 3 . join()方法在哪個線程被調用,則就插入到哪個線程前面. 此可實現插隊 和 合並 package com.qf.demo3; /** * join 插隊 , 合並 * * @author Administrator * */ public class Test4 { public static void main(String[] args) { TwoDog twoDog = new TwoDog(); twoDog.start(); try { twoDog.join();// 二狗想要插隊 // 插隊到當前線程前面 } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } for (int i = 0; i < 100; i++) { System.out.println("主線程執行了"+i+"次"); } } } class TwoDog extends Thread{ @Override public void run() { for (int i = 0; i < 100; i++) { System.out.println("英文二狗執行了"+i+"次"); } } } 4 . 以下代碼實現合並 package com.qf.demo3; /** * join方法 插隊 合並 * 插隊到的是當前線程前面(join方法在哪線程中被調用的 , 插隊到哪個線程) * @author Administrator * */ public class Test5 { public static void main(String[] args) { First first = new First(); first.start(); try { first.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } for (int i = 0; i < 100; i++) { System.out.println("主線程執行了"+i+"次"); } } } class First extends Thread{ @Override public void run() { Second second = new Second(); second.start(); try { second.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } for (int i = 0; i < 100; i++) { System.out.println("第一個線程執行了"+i+"次"); } } } class Second extends Thread{ @Override public void run() { for (int i = 0; i < 100; i++) { System.out.println("第二個線程執行了"+i+"次"); } } } |