線程的sleep,join,yield方法

線程狀態轉換:


創建->start()->就緒狀態<-->調度->運行狀態->終止
|箭頭                |箭頭
|向上  |向下
   阻塞解除<-阻塞狀態<—導致阻塞的事件 


·sleep方法
   ·可以調用Thread的靜態方法:
    public static void sleep(long millis) throws InterruptedException


    使得當前線程休眠(暫停執行millis毫秒)
 
  ·由於是靜態方法,sleep可由類名直接調用:

Thread.sleep(....)


舉例:
<span style="font-size:14px;">public class TestTnterrupt {
	public static void main(String args[]) {
		MyThread myThread = new MyThread();
		thread.start();
		try{Thread.sleep(10000);}
		catch{InterruptedException e}{}
		thread.interrupt();//終止線程
	}
}
class MyThread extends Thread {
	public void run(){
		while(true){
			System.out.println("...."+new Date()+".....");
			try{
				sleep(1000);
			}catch(InterruptedException e){
			return;
			}
		}
	}
}</span>


.join方法


   ·合併某個線程


舉例:

<span style="font-size:14px;">public class TestJoin {
	public static void main(String args[]) {
		MyThread thread = new MyThread("adcdb");
		thread.start();
		try {
			thread.join();
		}catch(InterruptedException e) {}
		for(int i=0;i<10;i++) {
			System.out.println("i am main thread");
		}
	
	}
}
class MyThread extends Thread {
	MyThread(String s) {
		super(s);
	}
	public void run(){
		for(int i=0;i<10;i++) {
			System.out.println("i am "+getName());
		}
		try {
			sleep(1000);
		}catch(InterruptedException e) {
		return;
		}
	}
}
</span>

註釋:把MyThread線程執行完了再執行主線程


·yield方法


   .讓出CPU,給其他線程執行的機會


舉例:

<span style="font-size:14px;">public class TestYield {
	public static void main(String args[]) {
		MyThread t1 = new MyThread("t1");
		MyThread t2 = new MyThread("t2");
		t1.start();
		t2.start();
	}
}
class MyThread extends Thread {
	MyThread(String s) {
		super(s);
	}
	public void run() {
		for(int i=0;i<=100;i++) {
			System.out.println(getName()+": "+i);
			if(i%10==0) {
				yield();
			}
		}
	}
}</span>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章