執行緒安全與非執行緒安全
阿新 • • 發佈:2018-11-08
1、執行緒不共享資料
對同一資源,各個執行緒各自執行一遍,程式碼如下:
package com.zzm.th01;
/**
* 執行緒不共享資料
* Created by ming on 2017/6/15.
*/
public class th04 extends Thread{
//記錄資源總數
private int count = 4;
@Override
public void run() {
super.run();
count--;
System.out.println(Thread.currentThread().getName()+"執行->" +count);
}
public static void main(String[] args) {
th04 th = new th04();
th04 th1 = new th04();
th04 th2 = new th04();
th.start();
th1.start();
th2.start();
}
}
2、執行緒資料共享
這種情況會有非執行緒安全問題。需要加synchronized。程式碼如下:
package com.zzm.th01;
/**
* Created by ming on 2017/6/15.
*/
public class th05 extends Thread {
int count = 7;
@Override
synchronized public void run() {
super.run();
count--;
System.out.println(Thread.currentThread().getName()+"執行->"+count);
}
public static void main(String[] args) {
th05 th = new th05();
Thread th1 = new Thread(th,"執行緒1");
Thread th2 = new Thread(th,"執行緒2");
Thread th3 = new Thread(th,"執行緒3");
th1.start();
th2.start();
th3.start();
}
}