1. 錯誤的停止方式
- stop()(已經廢棄)
原因是stop會在線程沒有執行完的時候強行停止線程,清除監視器鎖的信息,如果一個線程計算一項工作完成一半突然停止,有可能導致數據不一致,與我們的期望不一致,可能導致線程安全問題
package com.example.thread;
public class StopThread extends Thread {
private int i = 0, j = 0;
@Override
public void run() {
synchronized (this) {
++i;
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
++j;
}
}
public void print() {
System.out.println("i=" + i + ",j=" + j);
}
public static void main(String[] args) throws InterruptedException {
StopThread thread = new StopThread();
thread.start();
Thread.sleep(1000);
thread.stop();
while (thread.isAlive()) {
}
thread.print();
}
}
- 我們可以利用 thread.interrupt(); 或者 flag標誌位去停止線程
- 利用thread.interrupt();
package com.example.thread;
public class InterruptThread extends Thread {
private int i = 0, j = 0;
@Override
public void run() {
synchronized (this) {
++i;
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
++j;
}
}
public void print() {
System.out.println("i=" + i + ",j=" + j);
}
public static void main(String[] args) throws InterruptedException {
InterruptThread thread = new InterruptThread();
thread.start();
Thread.sleep(1000);
thread.interrupt();
while (thread.isAlive()) {
}
thread.print();
}
}
- 利用標誌位,如果我們業務中有while循環,我們可以聲明一個volatile變量的編制爲flag=false,然後當條件達到時,在主線程中設置flag=true,停止子線程的運行