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;
			}
		}
	}
}

4
/**
 *  
 */
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();
	}
}

Google 번역으로 복사
번역 결과

좋은 웹페이지 즐겨찾기