关于线程不同步执行的问题

 public class TestSynchronous implements Runnable{
    Timer timer = new Timer();
    public static void main(String[] args){
        TestSynchronous test = new TestSynchronous();
        Thread t1 = new Thread(test);
        Thread t2 = new Thread(test);
        t1.setName("t1");
        t2.setName("t2");
        t1.start();
        t2.start();
    }

    public void run(){
        timer.add(Thread.currentThread().getName());
    }
}

class Timer{
    private static int num = 0;
    public void add(String name){
        num++;
        try{
            Thread.sleep(1);
        }catch(InterruptedException e){
            e.printStackTrace();
        }
        System.out.println(name+": " +"是第"+num+"线程");
    }
}

第一次在命令行编译执行时是这样:
图片说明
随着执行次数的增加,有时候输出变成这样了:
图片说明
下面这个图是总的执行次数,可以看出,有一个num输出为1:
图片说明

由于num是静态共享变量,但是同时被多个线程访问,所以必须对其作同步控制,修正你的Timer的add方法,把num++放在同步互斥代码块中保证同一时刻只能有一个线程对其修改,修改版如下:

synchronized(Timer. class){num++;}