單線程是安全的,因為線程只有一個,不存在多個線程搶奪同一個資源
代碼例子:
public class SingleThread {int num=10;public void add(){while(num<13){num++;try{Thread.sleep(1000);}catch(Exception e){System.out.println("中斷");}System.out.println(num);}}public static void main(String[] args){Thread thread = Thread.currentThread(); //獲取當前運行的線程對象thread.setName("單線程"); //線程重命名System.out.println(thread.getName()+"正在運行");SingleThread st=new SingleThread();st.add();}}多線程安全,synchronized同步代碼塊
synchronized(對象){}; //同步代碼塊
synchronized 返回值方法名(){}; //同步方法
class One { int num=10; public void add(){ synchronized(this){ //同步代碼塊,同步方法也可以實現效果synchronized void add(){};num++; try { Thread.sleep(1000); } catch (InterruptedException e) { System.out.println("中斷"); } System.out.println(num); } }}class Two implements Runnable{ One one = new One(); @Override public void run() { one.add(); //調用add方法}}public class Synch{ public static void main(String[] args) {Two two = new Two(); Thread t1 = new Thread(two); //創建三個子線程Thread t2 = new Thread(two); Thread t3 = new Thread(two); t1.start(); t2.start(); t3.start(); }}注意:觀察去除synchronized關鍵字的運行結果區別!
正常運行結果:
11
12
13