public class Test {
public static void main(String[] args) {
final ShareData data = new ShareData();
for (int i = 0; i < 2; i++) {
new Thread(new Runnable() {
public void run() {
try {
data.inc();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
for (int i = 0; i < 2; i++) {
new Thread(new Runnable() {
public void run() {
try {
data.dec();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
}
}
class ShareData {
private int i = 100;
public synchronized void inc() throws InterruptedException {
i++;
System.out.println(Thread.currentThread().getName() + "--inc--" + i);
}
public synchronized void dec() throws InterruptedException {
i--;
System.out.println(Thread.currentThread().getName() + "--dec--" + i);
}
}