日期:2014-05-20  浏览次数:20736 次

同步的方法synchronized 用于静态变量时的问题


class Wrapper {
int val=0;
}

public class t{
public static void main(String[]args) throws InterruptedException{
for (int q= 0;q<30;q++){
Thread t = new Thread (new tRunnable());
t.start();

}

}
}


class tRunnable implements Runnable {


static Wrapper self = new Wrapper();


public  void run(){
set1();
}

public synchronized void set1(){
for (int i = 1;i<50;i++)
{self.val = i;
System.out.println(self.val);
}
System.out.println("Finished!!!!!!!!!!!!!");
}

}


这个问题运行结果本该是从不停的1打印到50,但是我运行结果里却有这么一块:
20
21
22
23
24
1
2
3
4
这说明set1方法没有运行完就被剥夺运行权了,但是我的set方法是同步的啊,而且也是是修改静态域啊,这个域不是同一个类对象统一用一个嘛????
------最佳解决方案--------------------
引用:


正解,楼主没有共享一个对象锁,所以相当于没有锁。
在new Tread的时候传入同一个对象就好了!
或者把set1()改成static,用类锁也行。
------其他解决方案--------------------
你是在tRunnable对象上同步的,而 Thread t = new Thread (new tRunnable());每个线程都有自己的tRunnable,说白了,这个同步起不到互斥的作用
------其他解决方案--------------------
改一下就可以了:

    public static void main(String[]args) throws InterruptedException{
            tRunnable tr=new tRunnable();//产生一个Runnable对象。
            for (int q= 0;q<30;q++){
            Thread t = new Thread (tr);//多个线程公用一个Runnable对象。
            t.start();
             

------其他解决方案--------------------
同一楼的,你那个其实就等于创建了30个tRunnable,每个tRunnable内部的set方法可使实现同步,但是相互之间是不会的。