java多線程入門例子

假設一個場景:單人浴室,隨便想的一個場景。在被使用的時候,其餘人不能進入。一次最多進入一我的。而後,運行流程就是:一人進入,使用一段時間,出來;再次一人進入,使用一段時間,出來。如此循環。java

 

浴室類 BathRoom :多線程

import java.util.concurrent.TimeUnit;

public class BathRoom {
	/**Just one thread can invok this method at any time point.
	 * and only after invoked and released, any other thread can invok this method 
	 * @throws InterruptedException
	 */
	public synchronized void useBathRoom() throws InterruptedException {
		String threadName = Thread.currentThread().getName(); 
		System.out.println(threadName + " get into the bathroom......");
		TimeUnit.MILLISECONDS.sleep(500);// using the bathroom
		System.out.println(threadName + " get out of the bathroom......");
	}
}

 

People類,實現Runnable接口。ide

public class People implements Runnable {
	private BathRoom room;

	public People(BathRoom room) {
		this.room = room;
	}

	@Override
	public void run() {
		while (!Thread.interrupted()) {
			try {
				room.useBathRoom();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

 

測試類 Main:測試

public class Main {
	public static void main(String[] args) throws InterruptedException {
		BathRoom room = new BathRoom();//共享資源
		People p = new People(room);   // 
		  
		Thread zhangsan = new Thread(p, "zhangsan");
		Thread lisi = new Thread(p, "lisi");
		Thread wangwu = new Thread(p, "wangwu");
		
		zhangsan.start();  
		lisi.start();
		wangwu.start();
	}
}

 

運行結果:this

zhangsan get into the bathroom......
zhangsan get out of the bathroom......
wangwu get into the bathroom......
wangwu get out of the bathroom......
lisi get into the bathroom......
lisi get out of the bathroom......
wangwu get into the bathroom......
wangwu get out of the bathroom......
zhangsan get into the bathroom......
zhangsan get out of the bathroom......
zhangsan get into the bathroom......
zhangsan get out of the bathroom......
wangwu get into the bathroom......spa

 

 

分析:線程

多線程中有個很重要的概念:獨佔(鎖,資源只有一份,有多個線程競爭這一份僅有的資源,一旦線程拿到這個資源,資源將被鎖住,其餘線程只能等待 )。code

在BathRoom中,有synchronized 方法,synchronized 的做用是,在同一時刻,只能有一個線程來訪問這個方法。接口

在main方法中,建立了一個BathRoom實例,並且,整個程序中有且僅有一個BathRoom實例。而建立的zhangsan,lisi,wangwu線程,都是共用的這個實例。資源

也就是說,在任意時間點,這三個線程都會去競爭訪問這個實例中的惟一一個方法useBathRoom()。一旦有一個線程訪問到了這個方法, 其餘的線程就只能等待了。

相關文章
相關標籤/搜索