java synchronized死锁的好例子
来源:互联网 发布:sublime的js插件 编辑:程序博客网 时间:2024/05/29 13:41
关于java死锁的一个好demo。要避免dead-lock,就应该控制同步的数量和可能共用的资源的访问(代码源于网上,略加修改)
/** * @author yicong * @date 2016年3月22日 下午1:44:32 * @todo 死锁的经典例子 */public class DeadLock {public static void main(String[] args) {// These are the two resource objects we'll try to get locks forfinal Object resource1 = "resource1";final Object resource2 = "resource2";// Here's the first thread. It tries to lock resource1 then resource2Thread t1 = new Thread() {public void run() {// Lock resource 1synchronized (resource1) {System.out.println("Thread 1: locked resource 1");// Pause for a bit, simulating some file I/O or// something. Basically, we just want to give the// other thread a chance to run. Threads and deadlock// are asynchronous things, but we're trying to force// deadlock to happen here...try {Thread.sleep(50);}catch (InterruptedException e) {}// Now wait 'till we can get a lock on resource 2synchronized (resource2) {while (true) {System.out.println("Thread 1: locked resource 2");try {Thread.sleep(10000);}catch (InterruptedException e) {}}}}}};// Here's the second thread. It tries to lock resource2 then resource1Thread t2 = new Thread() {public void run() {// This thread locks resource 2 right awaysynchronized (resource2) {System.out.println("Thread 2: locked resource 2");// Then it pauses, just like the first thread.try {Thread.sleep(50);}catch (InterruptedException e) {}// Then it tries to lock resource1. But wait! Thread 1// locked resource1, and won't release it 'till it// gets a lock on resource2. This thread holds the// lock on resource2, and won't release it 'till it// gets resource1. We're at an impasse(僵局). Neither// thread can run, and the program freezes up.synchronized (resource1) {System.out.println("Thread 2: locked resource 1");}}}};// Start the two threads. If all goes as planned, deadlock will occur, and the program will never exit.t1.start();t2.start();}}
0 0
- java synchronized死锁的好例子
- synchronized 和 beginTransaction 死锁的一个例子
- java死锁的例子
- Java 死锁的例子
- Java死锁的例子
- Java的synchronized用法及死锁
- Java多线程死锁的例子
- java死锁的一个例子
- Java死锁的简单例子
- synchronized产生的死锁
- java Synchronized关键字和死锁
- Java版死锁的例子程序
- java写的一个死锁例子
- java 线程死锁的小例子
- java写一个死锁的简单例子
- java中的线程死锁的一个例子
- java多线程发生死锁的一个例子
- Java一个简单的死锁例子
- 高效的SQLSERVER分页查询(多种方案)
- IOS添加滑动手势
- 税率
- 大规模运行MongoDB应该知道的10件事
- hive 增加自定义udf
- java synchronized死锁的好例子
- KMP算法——Knuth–Morris–Pratt algorithm
- js+html实现遮罩层效果
- jsapi 调用创建企业会话和企业通讯录
- C语言存储类型
- VR影片制作
- 洛谷P1273 有线电视网
- Android分辨率适配layout布局的问题
- going deeper with convolution---googlenet