今日在研究线程同步和通信方面的问题,出现了线程死锁。我在这方面思路不是很清晰,请大哥们告诉我出现死锁的原因,和解决问题的步骤。谢谢了。
这道题目是这样的。
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();
}
}
貌似不符合线程死锁的那四个条件啊。