模拟2个线程操作共享资源时的如何交互

模拟2个线程操作共享资源时的如何交互

package thread;

/**
 * 简单的2个线程间交替执行示例
 * 通过synchronized保证对资源的“原子操作”不被打断 
 * 通过线程通信实现切换运行
 */
public class TwoThreadsCommunication {
	
	
	public static void main(String[] args) {
		
		new TwoThreadsCommunication().justDoIt();
		
	}
	
	public void justDoIt() {
		
		final ResourceHandler r = new ResourceHandler();
		
		
		new Thread(new Runnable() {
			public void run() {
				for(int i=0;i<100;i++)
					r.produce();
			}
		}, "线程A").start();
		
		new Thread(new Runnable() {
			public void run() {
				for(int i=0;i<100;i++)
					r.consume();
			}
		}, "线程B").start();
	}
	
	
	/**
	 * 资源类
	 * 
	 * 将多线程操作的代码单独封装起来,然后在run()中通过对象来调用
	 * 将同步放到资源上,而不是在run()中进行控制,实现与具体线程的解耦
	 * 互斥不要放到线程上进行,而应该放到对资源类操作的方法中!!!
	 */
	class ResourceHandler {
		
		//状态变量在资源内部进行操作
		private boolean full;
		
		//生产线程操作共享资源的方法
		public synchronized void produce() {
			//notice: 这里用while,不要用if。可防止死锁!
			while(full) {
				try {
					this.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			for(int i=1;i<=10;i++) {
				System.out.println(Thread.currentThread().getName()+" run***" + i);
			}
			full = true;
			this.notify();
		}
		
		//消费线程操作共享资源的方法
		public synchronized void consume() {
			//notice: 这里用while,不要用if。可防止死锁!
			while(!full) {
				try {
					this.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			for(int j=1;j<=10;j++) {
				System.out.println(Thread.currentThread().getName()+" run******" + j);
			}
			full = false;
			this.notify();
		}
		
	}
}

猜你喜欢

转载自just2learn.iteye.com/blog/2070602