1. 程式人生 > >多執行緒基礎二(執行緒的啟動、終止,執行緒面臨的三種問題)

多執行緒基礎二(執行緒的啟動、終止,執行緒面臨的三種問題)

一、執行緒的啟動、終止方式

  啟動: start native(呼叫外部介面啟動)

    終止:    stop(類似kill,暴力終止)  interrupt 中斷的方式 通過指令的方式 volatile boolean stop = false;

public class InterruptDemo {

private static int i;
public static void main(String[] args) {
Thread thread = new Thread(()->{
while(!Thread.currentThread().isInterrupted()){//判斷是否有interrupt標識
i++;
}
System.out.println(i);
},"interrupt");
thread.start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
thread.interrupt();//設定interrupt標識為true
System.out.println(Thread.interrupted());
}
}

二、執行緒的面臨的三大問題
  
(1)可見性問題
  
private volatile static boolean stop = false;可見性
//private static boolean stop = false;
//main主執行緒
public static void main(String[] args) throws InterruptedException {
//thread子執行緒
Thread thread = new Thread(()->{
int i = 0;
while (!stop){
i++;
}
System.out.println(i);
});
thread.start();
TimeUnit.SECONDS.sleep(1);
stop = true;//主執行緒改變值,子執行緒不可見,加上volatile後子執行緒可見
}

(2)原子性問題
    
private static int count = 0;

public static void inc(){
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
count++;
}
public static void main(String[] args) throws InterruptedException {

for (int i=0 ; i<1000;i++){
new Thread(AtomicDemo::inc).start();
}
Thread.sleep(4000);
System.out.println("執行結果:"+count);
}

執行結果卻不一定能夠是1000,之間相互影響

(3)有序性問題
根據編譯,快取的一致性問題等因素,程式的執行可能不會按照所編寫的執行。

JMM規範了上述執行緒的三個問題