O'Reilly logo

Java™ Phrasebook by Timothy Fisher

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required