synchronized
public class Sync{
class ThreadDemo extends Thread {
public int i;
public Sync sync;
public ThreadDemo(int i,Sync sync) {
this.i = i;
this.sync = sync;
}
@Override
public void run() {
super.run();
System.out.println(this.getName()+":"+i+"-"+new Date().getTime());
sync.pf(i);
}
}
public void pf(int i) {
try {
Thread.sleep(4000/i);
// wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.err.println(i+":"+new Date().getTime());
}
public static void main(String[] args) throws InterruptedException {
Sync sy = new Sync();
Thread th = sy.new ThreadDemo(1,sy);
th.setName("T-0");
Thread th1 = sy.new ThreadDemo(2,sy);
th1.setName("T-1");
th.start();
th1.start();
}
}
输出结果为:
T-0:1-1540263348943
T-1:2-1540263348943
2:1540263350943
1:1540263352943
T-0:执行消耗4s T-1执行消耗2s,说明同时执行pf()。
修改pf()方法:
public void pf(int i) {
synchronized(this){
try {
Thread.sleep(4000/i);
// wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.err.println(i);
}
}
执行结果:
T-1:2-1540263491240
T-0:1-1540263491241
2:1540263493241
1:1540263497241
T-1:消耗 2S T-0消耗6S 说明T-1先占用pf()方法执行完之后才释放的锁,之后T-0才进到pf()方法
@Override
public void run() {
super.run();
System.out.println(this.getName()+":"+i+"-"+new Date().getTime());
Sync sync = new Sync();
sync.pf(i);
}
run方法修改。
执行结果:
T-0:1-1540263718637
T-1:2-1540263718637
2:1540263720638
1:1540263722638
T-0消耗4S T-1消耗2S,发现T-0并没有对pf()方法进行上锁。问题在于synchronized(this){}锁的是这个类的实例对象。
public void pf(int i) {
synchronized(Sync.class){
try {
Thread.sleep(4000/i);
// wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.err.println(i+":"+new Date().getTime());
}
}
修改pf()方法其他不变
执行结果:
T-0:1-1540264086174
T-1:2-1540264086174
1:1540264090175
2:1540264092175
T-0消耗4S T-1消耗6S,发现T-0对pf()方法加了锁。run方法中还是Sync sync = new Sync();synchronized(Sync.class){}锁的是类对象。