class Data{
public int j = 0;
}
class Plus implements Runnable{
private Data data;
public Plus(Data data) {
this.data = data;
}
@Override
public void run() {
while (true){
synchronized (data){
try{
Thread.sleep(400);
data.j++;
System.out.println(Thread.currentThread().getName()+":"+data.j);
}catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
class Sub implements Runnable{
private Data data;
public Sub(Data data) {
this.data = data;
}
@Override
public void run() {
while(true){
synchronized (data){
try{
Thread.sleep(400);
data.j--;
System.out.println(Thread.currentThread().getName()+":"+data.j);
}catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public class AppTest {
public static void main(String[] args) {
Data data = new Data();
Plus plus = new Plus(data);
Sub sub = new Sub(data);
new Thread(plus,"加线程一").start();
new Thread(plus,"加线程二").start();
new Thread(sub,"减线程一").start();
new Thread(sub,"减线程二").start();
}
}