本帖最后由 周敏2011nc 于 2011-12-22 09:05 编辑
在网上找到一个新的办法,和大家分享分享:
package com.jx.thread.test;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ThreadConditionTest {
/**
* @param args
* 在执行的时候发现这样一个问题:
* 那就是这几个线程执行循环的次数以最少的循环次数那个线程为准
* 这里就是三次过后就会不再输出了,所以在一般的情况下外层的循环
* 次数一般情况下是一样的,不然可能会达不到效果,具体的次数要求可以在内部循环中完成
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
final Outputer outputer = new Outputer();
new Thread(new Runnable() {
public void run() {
try {
for (int i = 0; i < 3; i++) {
outputer.output1();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
new Thread(new Runnable() {
public void run() {
try {
for (int i = 0; i < 5; i++) {
outputer.output2();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
for (int i = 0; i < 7; i++) {
outputer.output3();
}
}
}
class Outputer {
Lock lock = new ReentrantLock();
Condition condition1 = lock.newCondition();
Condition condition2 = lock.newCondition();
Condition condition3 = lock.newCondition();
private int envent = 3;
public void output1() {
lock.lock();
try {
while (envent != 1) {
try {
condition1.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for (int i = 0; i < 10; i++) {
System.out.println("this is first print");
}
envent = 2;
condition2.signal();
} finally {
lock.unlock();
}
}
public void output2() {
lock.lock();
try {
while (envent != 2) {
try {
condition2.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for (int i = 0; i < 20; i++) {
System.out.println("this is second print");
}
envent = 3;
condition3.signal();
} finally {
lock.unlock();
}
}
public void output3() {
lock.lock();
try {
while (envent != 3) {
try {
condition3.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for (int i = 0; i < 30; i++) {
System.out.println("this is third print");
}
envent = 1;
condition1.signal();
} finally {
lock.unlock();
}
}
}
|