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
* */