class Worker implements Runnable{
@Override
public void run() {
String lock = "mylock";
synchronized(lock){//这里会同步吗?
try{Thread.sleep(100);}catch(Exception e){e.printStackTrace();}
Test1.count++;
System.out.println(Thread.currentThread().getName()+" count:"+Test1.count);
Test1.count--;
System.out.println(Thread.currentThread().getName()+" count:"+Test1.count);
}
}
}
public class Test1 {
public static int count = 0;
public static void main(String[] args) {
Worker worker = new Worker();
for(int i=0;i<10;i++){
Thread t = new Thread(worker);
t.start();
}
}
}

解决方案 »

  1.   

    1 首先肯定会是同步的
    2 Worker对象没有成员变量,谈线程安全我觉得谈不上
      

  2.   

    String lock = "mylock"; //同步
    String lock = new String("mylock"); //不同步
    第一个lock指向的是字符串池中的"mylock",10个线程都对同一个对象加锁。如果改为第二种,就不会同步了。
      

  3.   


    //上面的例子给的不好,稍微改一下:
    class Worker implements Runnable{
    public static int count = 0;
    @Override
    public void run() {
    String lock = "mylock";
    synchronized(lock){
    try{Thread.sleep(100);}catch(Exception e){e.printStackTrace();}
    count++;
    System.out.println(Thread.currentThread().getName()+" count:"+count);
    count--;
    System.out.println(Thread.currentThread().getName()+" count:"+count);
    }
    }
    }
    public class Test1 {

    public static void main(String[] args) {
    Worker worker = new Worker();
    for(int i=0;i<10;i++){
    Thread t = new Thread(worker);
    t.start();
    }
    }
    }
      

  4.   

    楼主最开始的写法,用到Worker的线程间没有线程安全的问题。但是在一个系统里,可能有其它线程会修改Test1的count变量值,所以楼主第二次又修改了代码,这次更安全了。
      

  5.   


    class Worker implements Runnable{
        @Override
        public void run() {
            String lock = "mylock";
            synchronized(lock){//这个加得锁为常量池中的mylock,所有线程都是这一把锁,所以同步
                try{Thread.sleep(100);}catch(Exception e){e.printStackTrace();}
                Test1.count++;
                System.out.println(Thread.currentThread().getName()+" count:"+Test1.count);
                Test1.count--;
                System.out.println(Thread.currentThread().getName()+" count:"+Test1.count);
            }
        }
    }
    public class Test1 {
        public static int count = 0;
        public static void main(String[] args) {
            Worker worker = new Worker();//相反,每次执行run方法都创建了一个新的对象锁,每个线程各自一把锁,没有同步
            for(int i=0;i<10;i++){
                Thread t = new Thread(worker);
                t.start();
            }
        }
    }