第一种代码:没有synchronized public class ThreadTest1Test { //main函数 public static void main(String[] args) { ThreadTest2 r = new ThreadTest2(); Thread t1 = new Thread(r); Thread t2 = new Thread(r); t1.start(); t2.start(); } } //线程函数 public class ThreadTest2 implements Runnable { private static int temp = 0; public void run() { this.add(); } public void add() { temp++; try { Thread.sleep(10); } catch (InterruptedException e) { } System.out.println(Thread.currentThread().getName() + " " + temp); } } //此时输出的结果是 //Thread-1 2 //Thread-0 2 加上synchronized public class ThreadTest1Test { //main方法 public static void main(String[] args) { ThreadTest2 r = new ThreadTest2(); Thread t1 = new Thread(r); Thread t2 = new Thread(r); t1.start(); t2.start(); } } public class ThreadTest2 implements Runnable {//线程函数 private static int temp = 0; public void run() { this.add(); } public synchronized void add() { temp++; try { Thread.sleep(10); } catch (InterruptedException e) { } System.out.println(Thread.currentThread().getName() + " " + temp); } } //结果为 //Thread-1 1 //Thread-0 2 第二种 public class ThreadTest1Test { //main方法 public static void main(String[] args) { Thread t1 = new Thread(new ThreadTest2()); Thread t2 = new Thread(new ThreadTest2()); t1.start(); t2.start(); } } public class ThreadTest2 implements Runnable {//线程函数 private static int temp = 0; public void run() { this.add(); } public synchronized void add() { temp++; try { Thread.sleep(10); } catch (InterruptedException e) { } System.out.println(Thread.currentThread().getName() + " " + temp); } } //输出的结果 //Thread-0 2 //Thread-1 2 注意比较第一种和第二种输出结果上的区别 特别是第二种 在创建线程类的时候是创建两个线程 而第一种 在创建线程类的时候创建一个