java多线程同步问题(生产者和消费者)典型例子


经典的问题:生产者消费者问题就充分体现并发处理,这里一生产电影和看电影进行描述

Movie类:

package practice0326testDeadLock;
/**
 * 生产者消费者问题
 * 信号灯机制进行处理
 * 
 *
 */
public class Movie {
	String movieName;
	boolean f = true;
	
	public synchronized void play(String movieName) {
		//先让其等待,再唤醒
		if(!f) {
		try {
			this.wait();
		} catch (InterruptedException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		}
		try {
			Thread.sleep(100);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		this.movieName = movieName;
		System.out.println("拍了一部电影"+movieName);
		this.notify();
		
		f = false;
		
	}
	
	public synchronized void view() {
		
		if(f) {
			try {
				this.wait();
			} catch (InterruptedException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
			try {
				Thread.sleep(10);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println("看了一部电影"+movieName);
			this.notifyAll();
			
			f = true;
			}
}


Player类:(生产电影)

package practice0326testDeadLock;

public class Player implements Runnable{
	private Movie movie ;
	public Player(Movie m ) {
		super();
		this.movie = m;
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		for(int i = 0; i < 20; i++) {
			try {
				Thread.sleep(10);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(i % 2 == 0) {
				movie.play("奥特曼!");
			}
			else {
				movie.play("暮光之城!");
			}
		}
	}
	
}

Viewer:(消费电影)

package practice0326testDeadLock;

public class Viewer implements Runnable{
	private Movie movie ;
	public Viewer(Movie movie ) {
		super();
		this.movie = movie;
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		for(int i = 0; i < 20; i++) {
			try {
				Thread.sleep(10);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			movie.view();
		}
	}
	
}

测试类:

package practice0326testDeadLock;

public class TestConsumerAndProducter {
	public static void main(String[] args) {
		Movie m = new Movie();
		Player player = new Player(m);
		Viewer viewer = new Viewer(m);
		Thread thread1 = new Thread(player);
		Thread thread2 = new Thread(viewer);
		thread1.start();
		thread2.start();
	}
}

测试截图:

java多线程同步问题(生产者和消费者)典型例子_第1张图片

你可能感兴趣的:(java多线程同步问题(生产者和消费者)典型例子)