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();
}
}
}
2 Worker对象没有成员变量,谈线程安全我觉得谈不上
String lock = new String("mylock"); //不同步
第一个lock指向的是字符串池中的"mylock",10个线程都对同一个对象加锁。如果改为第二种,就不会同步了。
//上面的例子给的不好,稍微改一下:
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();
}
}
}
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();
}
}
}