我是多线程的新手,当我阅读有关多线程的内容时,想到编写这个花哨的多线程代码来执行以下操作。
我的计数器类如下。
class Counter {
private int c = 0;
public void increment() {
System.out.println("increment value: "+c);
c++;
}
public void decrement() {
c--;
System.out.println("decrement value: "+c);
}
public int value() {
return c;
}
}
此 Counter 对象在两个线程之间共享。启动线程后,我需要执行以下操作。我希望 Thread2 等到 Thread1 将 Counter 对象的计数增加 1。完成后,线程 1 通知 thread2,然后 Thread1 开始等待 thread2 将值减 1。然后 thread2 启动并将值减 1 和再次通知thread1,然后thread2开始等待thread1。重复这个过程几次。
我怎样才能做到这一点。提前谢谢了。
我做了以下事情。
public class ConcurrencyExample {
private static Counter counter;
private static DecrementCount t1;
private static IncrementCount t2;
public static void main(String[] args) {
Counter counter = new Counter();
Thread t1 = new Thread(new IncrementCount(counter));
t1.start();
Thread t2 = new Thread(new DecrementCount(counter));
t2.start();
}
}
public class DecrementCount implements Runnable {
private static Counter counter;
public DecrementCount(Counter counter) {
this.counter = counter;
}
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
counter.decrement();
System.out.println("decreamented");
}
}
}
public class IncrementCount implements Runnable {
private static Counter counter;
public IncrementCount(Counter counter) {
this.counter = counter;
}
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
counter.increment();
System.out.println("Incremented");
}
}
}