java线程锁问题,求各位帮帮忙

yuzeng222 2016-07-30 07:55:38
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package jointest;
/**
*
* @author Admin
*/
public class JoinTest {
public static void main(String[] args) {
Thread t = new Thread( new RunnableImpl());
new ThreadTest(t).start();// 这个线程会持有锁
t.start();
try {
t.join();
System.out.println("joinFinish");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}


/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package jointest;
/**
*
* @author Admin
*/
class ThreadTest extends Thread {
Thread thread;
public ThreadTest(Thread thread) {
this .thread = thread;
}
@override
public void run() {
holdThreadLock();
}
public void holdThreadLock() {
synchronized (thread) {
System.out.println("getObjectLock");
try {
Thread.sleep(9000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
System.out.println("ReleaseObjectLock");
}
}
}


/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package jointest;
/**
*
* @author Admin
*/
class RunnableImpl implements Runnable {
@override
public synchronized void run() {
try {
System.out.println("Begin sleep");
Thread.sleep(2000);
System.out.println("End sleep");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}


运行输出的一种结果是这样的
getObjectLock
Begin sleep
End sleep
ReleaseObjectLock
joinFinish

为什么在new ThreadTest(t).start()这个线程上加了锁,new ThreadTest(t).start()这个线程还没有结束,线程t.start()就开始运行了?
...全文
385 5 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
yuzeng222 2016-08-06
  • 打赏
  • 举报
回复
还有点不明白,为什么System.out.println("joinFinish")这输出语句,是在线程new ThreadTest(t).start()运行结束后才输出,而不是在 t.start()线程运行结束后就输出,请大神们帮忙解答一下,谢谢了!
yuzeng222 2016-08-05
  • 打赏
  • 举报
回复
谢谢2楼、3楼的大神
rickylin86 2016-08-04
  • 打赏
  • 举报
回复
另个线程是基于不同的对象进行同步的. new ThreadTest(t) 是基于t这个实例对象同步. Thread t = new Thread( new RunnableImpl()); t是基于内部的RunableImp实例对象来同步
HD_XB 2016-08-04
  • 打赏
  • 举报
回复
Thread t = new Thread( new RunnableImpl()); 对象锁是 RunnableImpl对象 new ThreadTest(t).start(); 对象锁是 t 对象 这两个锁不是同一个对象
yuzeng222 2016-08-04
  • 打赏
  • 举报
回复
求大神帮忙解答,谢谢了!

62,634

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧