设计4个线程,其中两个线程每次对j增加1,另外两个线程对j每次减少1。
public class TestThreads {
private static int j = 1;
//加线程
private static class Inc implements Runnable{
public void run(){
for(int i=0;i<10;i++){
inc();
}
}
}
//减线程
private static class Dec implements Runnable{
public void run(){
for(int i=0;i<10;i++){
dec();
}
}
}
//加1
private static synchronized void inc(){
j++;
System.out.println(Thread.currentThread().getName()+"-inc"+j);
}
//减1
private static synchronized void dec(){
j--;
System.out.println(Thread.currentThread().getName()+"-dec"+j);
}
public static void main(String[] args) {
//启动4个线程
for(int i=0;i<2;i++){
new Thread(new Inc()).start();
new Thread(new Dec()).start();
}
}
}