Pausing a Thread

MyThread thread = new MyThread();
											thread.start();
											while (true) {
											// do work...
											synchronized (thread) {
											thread.doWait = true;
											}
											// do work...
											synchronized (thread) {
											thread.doWait = false;
											thread.notify();
											}
											}
											class MyThread extends Thread {
											boolean doWait = false;
											public void run() {
											while (true) {
											// do work...
											synchronized (this) {
											while (doWait) {
											wait();
											}
											catch (Exception e) {
											}
											}
											}
											}
											}
											}

This phrase shows you how to pause a thread from a different thread. In the phrase, we use the variable doWait as a flag to pause the execution of MyThread. In the run() method of MyThread, we check the doWait flag after performing some work in a loop to determine if we need to pause the thread’s execution. If the doWait flag is set to ...

Get Java™ Phrasebook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.