51,397
社区成员




// 负责增加的
Runnable adder = new Runnable() {
public void run() {
for (int i = 0; i < 1e5; i++) {
inc();
System.out.println(counter);
}
}
};
// 负责减少的
Runnable decer = new Runnable() {
public void run() {
for (int i = 0; i < 1e5; i++) {
dec();
System.out.println(counter);
}
}
};
public class MultiIncDec {
private static int counter = 0;
public static void main(String[] args) {
// 负责增加的
Runnable adder = new Runnable() {
public void run() {
for (int i = 0; i < 1e6; i++)
inc();
}
};
// 负责减少的
Runnable decer = new Runnable() {
public void run() {
for (int i = 0; i < 1e6; i++)
dec();
}
};
// 定义线程
Thread[] ts = new Thread[4];
ts[0] = new Thread(adder);
ts[1] = new Thread(adder);
ts[2] = new Thread(decer);
ts[3] = new Thread(decer);
// 启动
for (Thread t:ts) {
t.start();
}
// 等待结束
for (Thread t:ts) {
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 输出结果
System.out.println("Result: " + counter);
}
public static synchronized void inc() {
counter++;
}
public static synchronized void dec() {
counter--;
}
}