線程同步的簡單示例

class MyThread implements Runnable{
	int i=100;
	public void run(){
		while(true){
			synchronized(this){//線程同步關鍵字
				System.out.println(Thread.currentThread().getName()+i);
				i--;
				Thread.yield();
				if(i<0){
					break;
				}
			}
		}
	}
}


class Test{
	public static void main(String args[]){
		MyThread myThread=new MyThread();
		Thread t1=new Thread(myThread);
		Thread t2=new Thread(myThread);
		t1.setName("t1-->");
		t2.setName("t2-->");
		t1.start();
		t2.start();
	}
}


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