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()。一旦有一个线程访问到了这个方法, 其余的线程就只能等待了。

相关文章
相关标签/搜索