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

public class ThreadTest {

private int j = 1;

//+1
private synchronized void n(){
j++;
System.out.println(Thread.currentThread().getName()+"n:"+j);
}

//-1
private synchronized void m(){
j--;
System.out.println(Thread.currentThread().getName()+"m:"+j);
}

//加线程
private class N implements Runnable{
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i < 10; i++) {
n();
}
}
}

//减线程
private class M implements Runnable{
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i < 10; i++) {
m();
}
}
}

public static void main(String[] args) {
ThreadTest tt = new ThreadTest();
//创建2个线程类
Thread t = null;
N n = tt.new N();
M m = tt.new M();
//启动4个线程
for (int i = 0; i <2; i++) {
t=new Thread(n);
t.start();
t=new Thread(m);
t.start();
}
}

}

原文地址:https://www.cnblogs.com/Yxxxxx/p/6854697.html