java 同步块疑惑

默默坚持 默默坚持 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
自己在学习多线程,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.......
...全文
评论 9
收藏 已收藏
分享
返回顶部
默默坚持
Java SE 62,620 成员 307,251 内容