设计 4 个线程,其中两个线程每次对 j 增加 1,另外两个线程对 j 每次减少 1。写出程序。

时间:2024-04-30 23:15:45

先设计一个类处理加减这一行为:

public class ManyThread {

    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 ManyThread manyThread = new ManyThread();

    public static void main(String[] args) {

        MyTest myTest = new MyTest();
myTest.test(); } public void test() {
for(int i = 0; i < 2;i++){
new Thread(new Runnable() { @Override
public void run() {
for (int i = 0;i < 20;i++){
manyThread.inc();
} }
}).start();
new Thread(new Runnable(){ @Override
public void run() {
for(int i = 0;i < 20;i++){
manyThread.dec();
}
}
}).start();
}
}
}