代码你可以这样写:
public class ThreadIncDec {
private int j;
public static void main(String[] args) {
ThreadIncDec incDec = new ThreadIncDec();
Inc inc = incDec.new Inc();
Dec dec = incDec.new Dec();
for (int i = 0; i < 2; i++) {
Thread t = new Thread(inc);
t.start();
t = new Thread(dec);
t.start();
}
}
//计数加一
private synchronized void inc() {
j++;
System.out.println(Thread.currentThread().getName() + "-inc:" + j);
}
//计数减一
private synchronized void dec() {
j--;
System.out.println(Thread.currentThread().getName() + "-dec:" + j);
}
//内部类实现的线程,线程对计数器加一
class Inc implements Runnable {
public void run() {
for (int i = 0; i < 100; i++) {
inc();
}
}
}
//内部类实现的线程,线程对计数器减一
class Dec implements Runnable {
public void run() {
for (int i = 0; i < 100; i++) {
dec();
}
}
}
}
|