java 同步块疑惑
默默坚持 2014-12-02 11:12:33 自己在学习多线程,synchronized关键字能获取对象的锁,但我测试结果让我还疑惑,同时有2个thread都能进入同步块中,但如果不使用wait、notify,就只能就一个thread进入同步块,请熟悉多线程的牛人帮忙解答下。
public class test {
public static void main(String[] args) {
Object lockObject = new Object();
ThreadT threadT = new ThreadT("thread test1",lockObject);
ThreadT threadW = new ThreadT("thread test2",lockObject);
Thread thread1 = new Thread(threadT);
Thread thread2 = new Thread(threadW);
thread1.start();
thread2.start();
}
}
class ThreadT implements Runnable{
private String name = "";
private Object objectlock = null;
public ThreadT(String name,Object objectlock){
this.name = name;
this.objectlock = objectlock;
}
@Override
public void run() {
synchronized(objectlock){
// TODO Auto-generated method stub
try {
System.out.println(name+" get the lock");
objectlock.wait(1000);
System.out.println(name+" running.......");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
objectlock.notify();
}
}
}
}
输出结果:
thread test1 get the lock
thread test2 get the lock
等待1秒后输出
thread test1 running.......
thread test2 running.......
如果把run方法修改为,
public void run() {
synchronized(objectlock){
// TODO Auto-generated method stub
//try {
System.out.println(name+" get the lock");
// objectlock.wait(3000);
System.out.println(name+" running.......");
//} catch (InterruptedException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
//}
//finally{
// objectlock.notify();
//}
}
}
执行结果为:
thread test1 get the lock
thread test1 running.......
thread test2 get the lock
thread test2 running.......