package com.com.aaa.addreduceThread;
public class ThreadDemo {
private int j=1;
//每次添加1
private synchronized void ad(){
j++;
System.out.println("添加"+j);
}
//每次减少1
private synchronized void red(){
j--;
System.out.println("减少"+j);
}
private class Add implements Runnable{
@Override
public void run() {
for (int i=0;i<5;i++){
ad();
}
}
}
private class Reduce implements Runnable{
@Override
public void run() {
for (int i=0;i<5;i++){
red();
}
}
}
public static void main(String[] args) {
ThreadDemo td=new ThreadDemo();
Thread t=null;
Add a=td.new Add();
Reduce r=td.new Reduce();
for (int i=0;i<2;i++){
t=new Thread(a);
t.start();
t=new Thread(r);
t.start();
}
}
}
运行结果: