Java多線程 生產者消費者模式

/**
 * 公共的資源(多個線程操作的對象)
 */
public class Info {

	private boolean b = false;
	private String name = "小白";
	private int age = 22;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public synchronized void set(String name, int age) {
		if (!b) {
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		this.name = name;
		try {
			Thread.sleep(500);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		this.age = age;
		b = false;
		notifyAll();
	}

	public synchronized void get() {
		if (b) {
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		try {
			Thread.sleep(500);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(this.getName() + "--" + this.getAge());
		b = true;
		notifyAll();
	}
}

/**
 * 生產者
 */
public class Producer implements Runnable {
	private Info info = null;

	Producer(Info info) {
		this.info = info;
	}

	@Override
	public void run() {
		boolean b = false;
		for (int i = 0; i <= 10; i++) {
			if (b) {
				this.info.set("小白", 22);
				b = false;
			} else {
				this.info.set("小黑", 66);
				b = true;
			}
		}
	}
}

/**
 * 消費者
 */
public class Consumer implements Runnable {
	private Info info = null;

	public Consumer(Info info) {
		this.info = info;
	}

	@Override
	public void run() {
		for (int i = 0; i <= 10; i++) {
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			this.info.get();
		}
	}
}
測試類
public class TestMain {
	public static void main(String[] args) {
		Info info = new Info();
		Producer pro = new Producer(info);
		Consumer con = new Consumer(info);
		new Thread(pro).start();
		new Thread(con).start();
	}
}


發佈了52 篇原創文章 · 獲贊 12 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章