본문 바로가기

콩's EDUCATION/콩's JAVA_RUN

thread 예제 2

package thread;

// SharedCellSync.java
public class SharedCellSync {
public static void main(String args[]) {
	holdInteger h = new holdInteger();
	produceInteger p = new produceInteger(h);
	consumeInteger c = new consumeInteger(h);
	p.start();
	c.start();
}
}

class produceInteger extends Thread {
	private holdInteger pHold;

	public produceInteger(holdInteger h) {
		pHold = h;
	}

	public void run() {
		for (int count = 0; count < 10; count++) {
			pHold.setSharedInt(count);

			try {
				sleep((int) (Math.random() * 3000));
			} catch (InterruptedException e) {
				System.out.println("Exception:" + e.toString());
			}
		}
	}
}

class consumeInteger extends Thread {
	private holdInteger cHold;

	public consumeInteger(holdInteger h) {
		cHold = h;
	}

	public void run() {
		int val;
		val = cHold.getSharedInt();

		while (val != 9) {
			try {
				sleep((int) (Math.random() * 3000));
			} catch (InterruptedException e) {
				System.out.println("Exception : " + e.toString());
			}
			val = cHold.getSharedInt();

		}
	}
}

class holdInteger {
	private int SharedInt;
	private boolean available = false;

	public synchronized void setSharedInt(int val) {

		while (available == true) {
			try {
				wait();
			} catch (InterruptedException e) {
			}
		}
		SharedInt = val;
		available = true;
		System.out.println("producer에 의해 " + SharedInt + "저장");
		notify();

	}

	public synchronized int getSharedInt() {

		while (available == false) {
			try {
				wait();
			} catch (InterruptedException e) {
			}
		}
		available = false;

		System.out.println("consumer에 의해 " + SharedInt + "읽기");
		notify();

		return SharedInt;
	}
}