濡備綍鏆傚仠涓€涓鍦ㄨ繍琛岀殑绾跨▼
瑕佹殏鍋滀竴涓鍦ㄨ繍琛岀殑绾跨▼锛屽彲浠ヤ娇鐢═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>
相关问答