1. 程式人生 > 資訊 >微博迴應被列入“預摘牌名單”:繼續監測市場發展並評估所有戰略選擇

微博迴應被列入“預摘牌名單”:繼續監測市場發展並評估所有戰略選擇

/**
* 示例- 執行緒stop強制性中止,破壞執行緒安全的示例
*/
public class Demo3 {
public static void main(String[] args) throws InterruptedException {
StopThread thread = new StopThread();
thread.start();
// 休眠1秒,確保i變數自增成功
Thread.sleep(1000);
// 暫停執行緒
thread.stop(); // 錯誤的終止
// thread.interrupt(); // 正確終止
while (thread.isAlive()) {
// 確保執行緒已經終止
} // 輸出結果
thread.print();
}
}

public class StopThread extends Thread {
private int i = 0, j = 0;

@Override
public void run() {
synchronized (this) {
// 增加同步鎖,確保執行緒安全
++i;
try {
// 休眠10秒,模擬耗時操作
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
++j;
}
}

/** * 列印i和j */
public void print() {
System.out.println("i=" + i + " j=" + j);
}
}

/** 通過狀態位來判斷 */
public class Demo4 extends Thread {
public volatile static boolean flag = true;

public static void main(String[] args) throws InterruptedException {
new Thread(() -> {
try {
while (flag) { // 判斷是否執行
System.out.println("執行中");
Thread.sleep(1000L);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
// 3秒之後,將狀態標誌改為False,代表不繼續執行
Thread.sleep(3000L);
flag = false;
System.out.println("程式執行結束");
}
}