绾跨▼ " />

扫描二维码下载沐宇APP

沐宇

微信扫码使用沐宇小程序

沐宇

濡備綍鏆傚仠涓€涓鍦ㄨ繍琛岀殑绾跨▼

扬州沐宇科技
2023-09-28 10:56:53
绾跨▼

瑕佹殏鍋滀竴涓鍦ㄨ繍琛岀殑绾跨▼锛屽彲浠ヤ娇鐢═hread绫荤殑suspend()鏂规硶灏嗙嚎绋嬫寕璧凤紝鐒跺悗浣跨敤resume()鏂规硶鎭㈠绾跨▼鐨勬墽琛屻€?/p>

浠ヤ笅鏄竴涓ず渚嬩唬鐮侊細

public class MyRunnable implements Runnable {
private boolean isPaused = false;
public synchronized void pause() {
isPaused = true;
}
public synchronized void resume() {
isPaused = false;
notify();
}
@Override
public void run() {
while (true) {
synchronized (this) {
while (isPaused) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
// 绾跨▼鐨勬墽琛岄€昏緫
System.out.println("Thread is running");
}
}
}

鍦ㄤ笂杩颁唬鐮佷腑锛岄€氳繃娣诲姞isPaused瀛楁鏉ユ帶鍒剁嚎绋嬬殑鏆傚仠鍜屾仮澶嶃€?code>pause()鏂规硶灏?code>isPaused璁剧疆涓?code>true锛?code>resume()鏂规硶灏?code>isPaused璁剧疆涓?code>false骞惰皟鐢?code>notify()鏂规硶鏉ュ敜閱掔嚎绋嬨€?/p>

浠ヤ笅鏄浣曚娇鐢ㄤ笂杩颁唬鐮佹殏鍋滃拰鎭㈠绾跨▼锛?/p>

public class Main {
public static void main(String[] args) throws InterruptedException {
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
// 鏆傚仠绾跨▼
runnable.pause();
// 绾跨▼鏆傚仠鍚庢墽琛屽叾浠栭€昏緫
System.out.println("Thread is paused");
// 鎭㈠绾跨▼
runnable.resume();
// 绾跨▼鎭㈠鍚庣户缁墽琛?/span>
}
}

鍙互鏍规嵁鍏蜂綋闇€姹傛潵鍒ゆ柇浣曟椂鏆傚仠鍜屾仮澶嶇嚎绋嬬殑鎵ц銆?/p>

扫码添加客服微信