日期:2014-05-20 浏览次数:20737 次
package threadTest;
public class TestThread {
/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
Counter counter = new Counter();
Thread t1 = new Thread(new Adder(counter));
Thread t2 = new Thread(new Adder(counter));
Thread t3 = new Thread(new Adder(counter));
Thread t4 = new Thread(new Subtracter(counter));
Thread t5 = new Thread(new Subtracter(counter));
Thread t6 = new Thread(new Subtracter(counter));
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
t6.start();
// CyclicBarrier cb = new CyclicBarrier(6);
synchronized (counter) {
while (Counter.getCondition() < 6) {
// System.out.println(Counter.getCondition());
counter.wait();
}
}
System.out.println(Counter.getId());
System.out.println("main end");
}
}
class Adder implements Runnable {
private Object o;
public Adder(Object o) {
this.o = o;
}
@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i < 10000; i++)
Counter.addId();
synchronized (o) {
Counter.addCondition();
System.out.println(Thread.currentThread().getName() + " end");
if (Counter.getCondition() == 6)
o.notify();
}
}
}
class Subtracter implements Runnable {
private Object o;
public Subtracter(Object o) {
this.o = o;
}
@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i < 1000; i++)
Counter.subtractId();
synchronized (o) {
Counter.addCondition();
System.out.println(Thread.currentThread().getName() + " end");
if (Counter.getCondition() == 6)
o.notify();
}
}
}
class Counter {
private static int id = 1000;
private static int condition = 0;
public synchronized static int getCondition() {
return condition;
}
public synchronized static void addCondition() {
condition++;
System.out.println("condition=" + condition);
}
public static void addId() {
id++;
}
public static void subtractId() {
id--;
}
public static int getId() {
return id;
}
public static void setId(int id) {
Counter.id = id;
}
}