JAVA編程思想第四版-多線程的練習答案之練習11

exercise.exercise11.Number.JAVA

package exercise.exercise11;

public class Number{

	private int x;
	private int y;

	public Number(int x, int y) {
		this.x = x;
		this.y = y;
	}

	public Number() {
		
	}

	/**
	 * 不正確的數據域狀態創建!
	 */
	public void Inc() {
		
		if(x>100000){//如果x大於100000,y無法等於x了。故需要重置x和y,讓線程有退出的機會
			x = 1;
			y = 10000;
		}else{
			x+=2;
			y++;
		}
	}

	public void print(){
		System.out.println(Thread.currentThread().getName()+">>>X = "+this.x + " y ="+this.y);
	}
	
	public int getX() {
		return x;
	}

	public int getY() {
		return y;
	}
	
	

	public void setX(int x) {
		this.x = x;
	}

	public void setY(int y) {
		this.y = y;
	}
}

exercise.exercise11.PrintResultThread.JAVA

public class PrintResultThread extends Thread {

	Number number;

	public PrintResultThread(String name, Number number) {
		super(name);
		this.number = number;
	}

	/**
	 * @param args
	 */

	@Override
	public void run() {
		while (true) {
			//synchronized (number) {
				number.Inc();
				if ((number.getX() == number.getY())) {
					System.out.println("線程名爲:"
							+ Thread.currentThread().getName()
							+ "的線程已經計算出了x和y的值相等時,他們的值爲:");
					number.print();
					return;
				}
			//}
		}
	}
}
exercise.exercise11.MainThread.JAVA
public class MainThread {
	public static void main(String[] args) {
		Number num = new Number();
		num.setX(1);
		num.setY(10001);
		new PrintResultThread("Thread " + 1, num).start();
		new PrintResultThread("Thread " + 2, num).start();
		new PrintResultThread("Thread " + 3, num).start();
		new PrintResultThread("Thread " + 4, num).start();
		new PrintResultThread("Thread " + 5, num).start();
	}
}
/***未使用synchronized關鍵字時的輸出
線程名爲:Thread 1的線程已經計算出了x和y的值相等時,他們的值爲:
線程名爲:Thread 3的線程已經計算出了x和y的值相等時,他們的值爲:
Thread 3>>>X = 37579 y =29625
Thread 1>>>X = 51237 y =35816
線程名爲:Thread 2的線程已經計算出了x和y的值相等時,他們的值爲:
線程名爲:Thread 5的線程已經計算出了x和y的值相等時,他們的值爲:
Thread 5>>>X = 21949 y =21008
Thread 2>>>X = 21357 y =20696
線程名爲:Thread 4的線程已經計算出了x和y的值相等時,他們的值爲:
Thread 4>>>X = 19999 y =19999
*/
/**使用synchronized關鍵字時的輸出
線程名爲:Thread 5的線程已經計算出了x和y的值相等時,他們的值爲:
Thread 5>>>X = 20001 y =20001
線程名爲:Thread 2的線程已經計算出了x和y的值相等時,他們的值爲:
Thread 2>>>X = 19999 y =19999
線程名爲:Thread 4的線程已經計算出了x和y的值相等時,他們的值爲:
Thread 4>>>X = 19999 y =19999
線程名爲:Thread 3的線程已經計算出了x和y的值相等時,他們的值爲:
Thread 3>>>X = 19999 y =19999
線程名爲:Thread 1的線程已經計算出了x和y的值相等時,他們的值爲:
Thread 1>>>X = 19999 y =19999
 * */


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章