一个类的两个对象,在线程中改变了其中一个对象中的变量的值为什么另一个对象中的值也变了
展开全部
public class ThreadTest1 implements Runnable {
protected ThreadTest1 obj = null;
protected int snd = 0;
private boolean isRun = true;
public boolean isRun() {
return isRun;
}
public void stopRun() {
isRun = false;
}
public ThreadTest1() {
}
public ThreadTest1(ThreadTest1 o) {
obj = o;
}
protected void count() {
try {
Thread.sleep(100);
snd += 100;
System.out.println(this.toString() + " started " + snd +
" milisecond");
} catch (Exception e) {}
}
public void run() {
// TODO Auto-generated method stub
while(isRun()) {
count();
}
}
}
//
public class ThreadTest2 extends ThreadTest1 {
public ThreadTest2() {}
public ThreadTest2(ThreadTest1 o) {
super(o);
// TODO Auto-generated constructor stub
}
public void run() {
while(isRun()) {
super.count();
if (snd >= 3000 && obj != null) {
obj.stopRun();
stopRun();
}
}
}
}
//
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ThreadTest1 test1 = new ThreadTest1();
ThreadTest2 test2 = new ThreadTest2(test1);
Thread t1 = new Thread(test1);
Thread t2 = new Thread(test2);
t1.start();
t2.start();
}
}
protected ThreadTest1 obj = null;
protected int snd = 0;
private boolean isRun = true;
public boolean isRun() {
return isRun;
}
public void stopRun() {
isRun = false;
}
public ThreadTest1() {
}
public ThreadTest1(ThreadTest1 o) {
obj = o;
}
protected void count() {
try {
Thread.sleep(100);
snd += 100;
System.out.println(this.toString() + " started " + snd +
" milisecond");
} catch (Exception e) {}
}
public void run() {
// TODO Auto-generated method stub
while(isRun()) {
count();
}
}
}
//
public class ThreadTest2 extends ThreadTest1 {
public ThreadTest2() {}
public ThreadTest2(ThreadTest1 o) {
super(o);
// TODO Auto-generated constructor stub
}
public void run() {
while(isRun()) {
super.count();
if (snd >= 3000 && obj != null) {
obj.stopRun();
stopRun();
}
}
}
}
//
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ThreadTest1 test1 = new ThreadTest1();
ThreadTest2 test2 = new ThreadTest2(test1);
Thread t1 = new Thread(test1);
Thread t2 = new Thread(test2);
t1.start();
t2.start();
}
}
追问
为什么。谢谢
本回答被网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询