欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

4个线程,其中两个线程每次对j增加1,另外两个线程对j每次减少

程序员文章站 2022-07-12 21:26:54
...
public class Maintest {
private int j=0;

public static void main (String [] args){
Maintest mt = new Maintest();
add add = mt.new add();
dec dec = mt.new dec();
for (int i=0;i<2;i++){
Thread t = new Thread(add);
t.start();
t = new Thread(dec);
t.start();
}
}

private synchronized void add(){
j++;
System.out.println(Thread.currentThread().getName() +" _add is " +j);
}

private synchronized void dec(){
j--;
System.out.println(Thread.currentThread().getName() +" _dec is " +j);
}

class add implements Runnable{
public void run() {
for(int i = 0;i<10;i++){
add();
}
}
}

class dec implements Runnable{
public void run() {
for(int i = 0;i<10;i++){
dec();
}
}
}

}