主类
public class Main {
public static void main(String args[]){
Thread a = new Thread(new TreadAdd());
Thread b = new Thread(new TreadAdd());
Thread c = new Thread(new TreadAdd());
a.start();
b.start();
c.start();
}
}
线程类
public class TreadAdd implements Runnable{
private int total = 100;
Object obj = new Object();
@Override
public void run() {
while(true){
synchronized(obj){
if(Variable.aa>0){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Variable.aa--;
System.out.println(Thread.currentThread().getName()+"the total is"+Variable.aa);
}
}
}
}
}
运行觉果如下
Thread-0the total is31
Thread-1the total is30
Thread-2the total is29
Thread-0the total is28
Thread-1the total is27
Thread-0the total is26
Thread-2the total is25
Thread-0the total is24
Thread-2the total is23
Thread-1the total is22
Thread-0the total is21
Thread-2the total is20
Thread-1the total is19
Thread-0the total is18
Thread-2the total is17
Thread-1the total is16
Thread-0the total is15
Thread-2the total is14
Thread-1the total is13
Thread-0the total is12
Thread-2the total is11
Thread-1the total is10
Thread-2the total is9
Thread-0the total is8
Thread-1the total is7
Thread-2the total is6
Thread-0the total is5
Thread-1the total is4
Thread-2the total is3
Thread-0the total is2
Thread-1the total is1
Thread-0the total is0
Thread-2the total is-1
Thread-1the total is-2
明明加了synchronized同步,为什么还会有-1和-2这种情况呢
原因是主类中创建了三次线程类将主类改为
public class Main {
public static void main(String args[]){
TreadAdd t = new TreadAdd();
Thread a = new Thread(t);
Thread b = new Thread(t);
Thread c = new Thread(t);
a.start();
b.start();
c.start();
}
}
就避免了这种情况。