public class deadlock {
/**一个简单的死锁类
* 在一个Runnable实现类中模拟两个进程的执行内容;
* 当flag == true时模块1(线程1)执行,先执行锁外程序(不受锁限制),再锁定锁1
* (str对象)执行100到1的输出,
* 然后锁定锁2(str1对象),即需要得到锁2才能继续执行;
* 当flag == false时模块2(线程2)执行,先锁定锁2(str1对象)执行1到100的输出,
* 然后锁定锁1(str对象),即需要得到锁1才能继续执行;
* 所以此时两个线程互相等待对方释放手里的锁,导致程序阻塞,造成死锁。
*/
public static void main(String[] args) {
// TODO 自动生成方法存根
deadtest tt0 = new deadtest();
// TxtThread tt1 = new TxtThread();
// TxtThread tt2 = new TxtThread();
// TxtThread tt3 = new TxtThread();
tt0.flag = false;
new Thread(tt0).start();
deadtest tt1 = new deadtest();
tt1.flag = true;
new Thread(tt1).start();
// new Thread(tt0).start();
// new Thread(tt0).start();
// new Thread(tt1).start();
// new Thread(tt2).start();
// new Thread(tt3).start();
}
}
class deadtest implements Runnable {
static String str = new String();
static String str2 = new String();
boolean flag;
public void run() {
if (flag == true) {
for (int i = 1; i <= 20; i++) {
try {
Thread.sleep(10);
} catch (Exception e) {
e.getMessage();
}
System.out.println("鎖之外");
}
synchronized (str) {
int num = 100;
while (num > 0) {
try {
Thread.sleep(10);
} catch (Exception e) {
e.getMessage();
}
System.out.println(Thread.currentThread().getName()
+ "this is 模块1锁1 " + num--);
}
synchronized (str2) {
int num2 = 100;
for (int j = 0; j <= num2; j++) {
try {
Thread.sleep(10);
} catch (Exception e) {
e.getMessage();
}
System.out.println(Thread.currentThread().getName()
+ "this is 模块1锁2 " + j);
}
}
}
}
if (flag == false) {
synchronized (str2) {
int num2 = 100;
for (int j = 0; j <= num2; j++) {
try {
Thread.sleep(10);
} catch (Exception e) {
e.getMessage();
}
System.out.println(Thread.currentThread().getName()
+ "this is 模块2锁2 " + j);
}
synchronized (str) {
int num = 100;
while (num > 0) {
try {
Thread.sleep(10);
} catch (Exception e) {
e.getMessage();
}
System.out.println(Thread.currentThread().getName()
+ "this is模块2锁1 " + num--);
}
}
}
}
}
}
死锁示例程序
最新推荐文章于 2023-04-26 15:02:11 发布