个人感觉还挺有趣的死锁

一只会写代码的猴子 2016-09-10 06:39:30
以前一听死锁,立刻就想到双重锁,今天发现了貌似没那么复杂,不多说,上代码
//测试类,不必多说
public class TestDeadLock implements Runnable{

public static void main(String[] args) {
//创建并启动新线程,不废话
TestDeadLock test = new TestDeadLock();
Thread tt = new Thread(test);
tt.start();
synchronized("lock"){
try {
//调用jion()方法,等待tt线程结束
tt.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("-------main方法被执行了--------");
}
}
//run方法,不必多说
@Override
public void run() {
try {
//等待一下,确保main方法先拿到锁
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized("lock"){
System.out.println("-------run方法被执行了--------");
}
}

}

也不知道有没有用,分享给大家。因为分享所以快乐!!!
...全文
263 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
huyiyu 2016-09-11
  • 打赏
  • 举报
回复
不过能想到这个应该算很吊的存在了
huyiyu 2016-09-11
  • 打赏
  • 举报
回复
这个其实也算双重锁的样子。 你试一下自己实现join
huyiyu 2016-09-11
  • 打赏
  • 举报
回复

class DeadLock extends Thread
{
	public static void main(String[] args )
	{
		DeadLock t1 =  new DeadLock();
		t1.start();
		t1.join1();
		System.out.println("main_over");
		
	}
	
	public void run()
	{
		System.out.println("run over");	
	}
	public synchronized void join1()
	{
		try{this.wait();}catch(InterruptedException e){}
	}
	public synchronized void start()
	{
		super.start();
		this.notify();
		System.out.println("startover");
	}
}

62,625

社区成员

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

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