多條線程並發執行,隨機切換,調用join()方法,會使當前線程所在的線程(一般主線程)凍結,直到當前線程結束,所在的線程才恢復繼續執行
class JoinTestDemo implements Runnable{ @Override public void run() { for(int x=0;x<=5;x++){ try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"===="+x); } } } public class JoinDemo { /** * @param args * @throws InterruptedException */ public static void main(String[] args) throws InterruptedException { JoinTestDemo join=new JoinTestDemo(); Thread t1=new Thread(join); Thread t2=new Thread(join); t1.start(); t2.start(); //上面兩個子線程交替執行,主線程凍結,t1走完才解凍 t1.join(); //顯示主線程 for(int x=0;x<=5;x++){ Thread.sleep(100); System.out.println(Thread.currentThread().getName()+"===="+x); } } }
線程的優先級,調用Thread對象的setPriority()方法,可以設置優先級,參數:1,5,10最明顯;Thread.MAX_PRIORITY,Thread.MIN_PRIORITY,Thread.NORM_PRIORITY
調用Thread.yield();可以暫時釋放執行權,達到線程平均運行的目的