我正在测试我的技能而不是线程行为.当我实现Runnable接口并同步run方法时,我得到了绝对的结果.但是,当我扩展Thread类时,结果是不可预测的.以下是两个案例.我认为,两种情况下的线程都使用相同的资源.
案例1 Runnable
class Counter{
int count;
public void doCount(){
count=count+1;
}
public int getCount(){
return count;
}
}
public class One implements Runnable{
Counter counter = new Counter(); // common object to be shared with two threads
public void run(){
synchronized (this) {
for(int i=0;i<10000;i++){
counter.doCount();
}
}
}
public static void main(String[] args) throws InterruptedException {
One one = new One();
Thread t1 = new Thread(one);// using same resource 'one'
Thread t2 = new Thread(one);// using same resource 'one'
t1.start();
t2.start();
Thread.sleep(2000); // to give both threads time to complete
System.out.println(one.counter.getCount());
}
}
案例2线程
class Counter{
int count;
public void doCount(){
count=count+1;
}
public int getCount(){
return count;
}
}
public class One extends Thread{
Counter counter; //common object to be shared with two threads
One(Counter counter){
this.counter = counter;
}
public void run(){
synchronized (this) {
for(int i=0;i<10000;i++){
counter.doCount();
}
}
}
public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();
One o1 = new One(counter);// using same resource counter
One o2 = new One(counter);// using same resource counter
o1.start();
o2.start();
Thread.sleep(2000); // to give both threads time to complete
System.out.println(counter.getCount());
}
}
对于案例1,我每次都输出20000.但对于案例2,我每次都会得到随机值.为什么会这样?情况2也在两个线程中使用相同的资源,那么为什么它们会停止同步.任何人都能解释一下……我疯了!
解决方法:
synchronized(this)有问题.在这种情况下,您有2个实例:o1和02. synchronized(counter)应该可以工作,但不是理想的解决方案.
理想情况下,只是为了测试,我会使用私人锁.
class Counter{
final Object lock= new Object();
int count;
public void doCount(){
synchronized (lock){
count=count+1;
}
}
public int getCount(){
synchronized (lock) {
return count;
}
}
}
比睡眠更好的方法是使用Thread.join()