單線程是安全的,因為線程只有一個,不存在多個線程搶奪同一個資源
代碼例子:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
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 返回值 方法名(){}; //同步方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
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
原文鏈接:https://www.idaobin.com/archives/839.html