当前位置: 代码迷 >> J2SE >> java 同步块不解
  详细解决方案

java 同步块不解

热度:40   发布时间:2016-04-23 20:06:39.0
java 同步块疑惑
本帖最后由 jiangpan007 于 2014-12-02 11:14:52 编辑
自己在学习多线程,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.......

------解决思路----------------------
test1 wait后释放了对象锁,test2得到对象锁,test2 wait又释放了,然后test1 print ,然后test2 print
------解决思路----------------------
引用:
objectlock.wait(2000)执行后,当前线程(线程A)挂起,等2000毫秒会尝试获取对象锁吧


不是。是立即释放对象锁,然后处于等待状态2000毫秒,时间到了,结束这个等待状态,然后试图再尝试获取锁,以便继续执行wait之后的语句。
  相关解决方案