public class TextSync implements Runnable {
/**
* @Vesine
* 多线程锁问题程序
* 2014年12月23日15:47:32
*/
Timer timer=new Timer();
public static void main(String[] args) {
Thread t1=new Thread(new TextSync());
Thread t2=new Thread(new TextSync());
t1.setName("MY Thread1");
t2.setName("MY Thread2");
t1.start();
t2.start();
}
public void run(){
timer.add(Thread.currentThread().getName());
}
}
public class Timer {
private static int num=0;
public synchronized void add(String name){
num++;
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(name+":你是第"+num+"个访问线程");
}
}
为什么加锁后程序运行结果仍为
MY Thread1:你是第2个访问线程
MY Thread2:你是第2个访问线程
synchronized 修饰方法时
“同时只能有一个线程访问当前方法”针对的是同一个对象。
你的例子里,每个TextSync 都new了自己的Timer,不是同一个对象,synchronized 修饰的方法同一时间只有自己的TextSync会访问,所以根本不存在锁竞争。
楼上正解,你这个是多个线程跑各自的Timer,可以修改成如下:
public class TextSync implements Runnable {
/**
* @Vesine
* 多线程锁问题程序
* 2014年12月23日15:47:32
*/
Timer timer=new Timer();
public static void main(String[] args) {
Thread t1=new Thread(new TextSync());
Thread t2=new Thread(new TextSync());
t1.setName("MY Thread1");
t2.setName("MY Thread2");
t1.start();
t2.start();
}
public void run(){
timer.add(Thread.currentThread().getName());
}
}
class Timer {
private static int num=0;
public void add(String name){
synchronized(Timer.class) {
num++;
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(name + ":你是第" + num + "个访问线程");
}
}
}
或者像下面:
public class TextSync implements Runnable {
public static final Object obj = new Object();
/**
* @Vesine
* 多线程锁问题程序
* 2014年12月23日15:47:32
*/
Timer timer=new Timer();
public static void main(String[] args) {
Thread t1=new Thread(new TextSync());
Thread t2=new Thread(new TextSync());
t1.setName("MY Thread1");
t2.setName("MY Thread2");
t1.start();
t2.start();
}
public void run(){
timer.add(Thread.currentThread().getName(), obj);
}
}
class Timer {
private static int num=0;
public void add(String name, Object obj){
synchronized (obj) {
num++;
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(name + ":你是第" + num + "个访问线程");
}
}
}
核心是让两个线程争用同一个对象。
问题在于在错误的锁上进行了同步。
对于使用某个对象的客户端代码,需要使用该对象本身作为锁。
synchronized 修饰方法时 ,同步锁指的是当前对象,也就是this,
Thread t1=new Thread(new TextSync());
Thread t2=new Thread(new TextSync());
这两行代码分别new 一个TextSync()对象,没有指向同一个所对象,所以方法就没加上锁;
二楼的最后一句话是最关键的:核心是让两个线程争用同一个对象。