java为什么会产生死锁_下面的Java代码会产生线程死锁,谁能告诉我为什么会死锁?如何解决?...

今日在研究线程同步和通信方面的问题,出现了线程死锁。我在这方面思路不是很清晰,请大哥们告诉我出现死锁的原因,和解决问题的步骤。谢谢了。

这道题目是这样的。

1线程连续执行10次后2线程连续执行100次 然后3线程连续执行30次。整个上述过程在重复50次

下面是出现死锁的代码

package com.seu.edu.condition;

import java.util.Date;

import java.util.concurrent.locks.Condition;

import java.util.concurrent.locks.Lock;

import java.util.concurrent.locks.ReentrantLock;

public class TriConditionCommunication {

/*

* 循环50次{ 1线程循环10次,2线程循环100次 ,3线程循环30次}

*/

static class Business {

private int shouldSub = 1;

Lock rwLock = new ReentrantLock();

Condition condition1 = rwLock.newCondition();

Condition condition2 = rwLock.newCondition();

Condition condition3 = rwLock.newCondition();

public void thread1(int i) {

// 防止伪唤醒 使用while

rwLock.lock();

try {

while (shouldSub != 1) {

try {

//this.wait();

condition1.await();

} catch (Exception e) {

e.printStackTrace();

}

}

for (int j = 0; j < 10; j++) {

System.out.println(i + " Thread1 execute " + j + " time");

}

shouldSub = 2;

//this.notify();

condition2.signal();

} catch (Exception e) {

} finally {

rwLock.unlock();

}

}

public void thread2(int i) {

rwLock.lock();

// 防止伪唤醒

try {

while (shouldSub != 2) {

try {

//this.wait();

condition2.await();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

for (int j = 0; j < 100; j++) {

System.out.println(i + " Thread2 execute " + j + " time");

}

shouldSub = 3;

//this.notify();

condition3.signal();

} catch (Exception e) {

} finally {

rwLock.unlock();

}

}

public void thread3(int i) {

rwLock.lock();

// 防止伪唤醒

try {

while (shouldSub!=3) {

try {

//this.wait();

condition3.await();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

for (int j = 0; j < 30; j++) {

System.out

.println(i + " Thread3 execute " + j + " time");

}

shouldSub = 1;

//this.notify();

condition1.signal();

} catch (Exception e) {

} finally {

rwLock.unlock();

}

}

}

public static void main(String[] args) {

final Business business = new Business();

new Thread(new Runnable() {

@Override

public void run() {

System.out.println("子线程"+new Date().getTime());

for (int i = 0; i < 50; i++) {

business.thread1(i);

}

}

}).start();

System.out.println("主线程" + new Date().getTime());

for (int i = 0; i < 50; i++) {

business.thread2(i);

}

new Thread(new Runnable() {

@Override

public void run() {

for (int i = 0; i < 50; i++) {

business.thread3(i);

}

}

}).start();

}

}

貌似不符合线程死锁的那四个条件啊。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值