public class ManyThreads2 {
private int j = 0;
public synchronized void inc() {
j++;
System.out.println(Thread.currentThread().getName() + "inc" + j);
}
public synchronized void dec() {
j--;
System.out.println(Thread.currentThread().getName() + "dec" + j);
}
}
public class MyTest {
private ManyThreads2 many = new ManyThreads2();
public static void main(String[] args) {
// TODO Auto-generated method stub
MyTest myTest = new MyTest();
myTest.test();
}
public void test() {
for (int i = 0; i < 2; i++) {
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i < 20; i++) {
many.inc();
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i < 20; i++) {
many.dec();
}
}
}).start();
}
}
}