本帖最后由 刘旭 于 2012-3-27 15:08 编辑
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class TraditionalThreadCommunication {
public static void main(String[] args) {
final Business business = new Business();
new Thread(new Runnable() {
public void run() {
for (int i = 1; i <= 50; i++) {
business.thread1(i);System.out.println("1");
}
}
}).start();
new Thread(new Runnable() {
public void run() {
for (int i = 1; i <= 50; i++) {
business.thread2(i);System.out.println("2");
}
}
}).start();
new Thread(new Runnable() {
public void run() {
for (int i = 1; i <= 50; i++) {
business.thread3(i);System.out.println("3");
}
}
}).start();
}
}
// 封装资源
class Business {
Lock lock = new ReentrantLock();
Condition key1 = lock.newCondition();
Condition key2 = lock.newCondition();
Condition key3 = lock.newCondition();
int beShould = 1;
public synchronized void thread1(int i) {
lock.lock();
while (beShould != 1) {
try {
key1.await();
} catch (Exception e) {
}
}
for (int j = 1; j <= 5; j++) {
System.out.println("thread1 thread : " + j + ",loop: " + i);
}
beShould = 2;
key2.signal();System.out.println("Test");
lock.unlock();
}
public synchronized void thread2(int i) {
lock.lock();
while (beShould != 2) {
try {
key2.await();
} catch (Exception e) {
}
}
for (int j = 1; j <= 10; j++) {
System.out.println("thread2 thread: " + j + ",loop: " + i);
}
beShould = 3;
key3.signal();
lock.unlock();
}
public synchronized void thread3(int i) {
lock.lock();
while (beShould != 3) {
try {
key3.await();
} catch (Exception e) {
}
}
for (int j = 1; j <= 15; j++) {
System.out.println("thread3 thread: " + j + ",loop: " + i);
}
beShould = 1;
key1.signal();
lock.unlock();
}
}
线程1循环5次,线程2循环10次,线程3循环20次。如此重复50次。 |