Difference between suspending and stoping thread in java
Answers
Answered by
2
I'm learning Thread in java.
The following example shows how to suspend, resume and stop threads:
class MyNewThread implements Runnable { Thread thrd; boolean suspended; boolean stopped; MyNewThread(String name) { thrd = new Thread(this, name); suspended = false; stopped = false; thrd.start(); } public void run() { System.out.println(thrd.getName() + " starting."); try { for(int i = 0; i<1000; i++) { System.out.print(i + " "); if(i%10 == 0) { System.out.println(); Thread.sleep(250); } synchronized(this) { while(suspended) { wait(); } if(stopped) break; } } } catch(InterruptedException ex) { System.out.println(thrd.getName() + " interrupted."); } System.out.println(thrd.getName() + " exiting."); } synchronized void mystop() { stopped = true; suspended = false; notify(); } synchronized void mysuspend() { suspended = true; } synchronized void myresume() { suspended = false; notify(); } } public class Suspend { public static void main(String[] args) { MyNewThread ob1 = new MyNewThread("My Thread"); try { Thread.sleep(1000); ob1.mysuspend(); System.out.println("Suspending Thread."); Thread.sleep(1000); ob1.myresume(); System.out.println("Resuming Thread."); Thread.sleep(1000); ob1.mysuspend(); System.out.println("Suspending Thread."); Thread.sleep(1000); ob1.myresume(); System.out.println("Resuming Thread."); Thread.sleep(1000); ob1.mysuspend(); System.out.println("Stopping Thread."); ob1.mystop(); } catch(InterruptedException ex) {
The following example shows how to suspend, resume and stop threads:
class MyNewThread implements Runnable { Thread thrd; boolean suspended; boolean stopped; MyNewThread(String name) { thrd = new Thread(this, name); suspended = false; stopped = false; thrd.start(); } public void run() { System.out.println(thrd.getName() + " starting."); try { for(int i = 0; i<1000; i++) { System.out.print(i + " "); if(i%10 == 0) { System.out.println(); Thread.sleep(250); } synchronized(this) { while(suspended) { wait(); } if(stopped) break; } } } catch(InterruptedException ex) { System.out.println(thrd.getName() + " interrupted."); } System.out.println(thrd.getName() + " exiting."); } synchronized void mystop() { stopped = true; suspended = false; notify(); } synchronized void mysuspend() { suspended = true; } synchronized void myresume() { suspended = false; notify(); } } public class Suspend { public static void main(String[] args) { MyNewThread ob1 = new MyNewThread("My Thread"); try { Thread.sleep(1000); ob1.mysuspend(); System.out.println("Suspending Thread."); Thread.sleep(1000); ob1.myresume(); System.out.println("Resuming Thread."); Thread.sleep(1000); ob1.mysuspend(); System.out.println("Suspending Thread."); Thread.sleep(1000); ob1.myresume(); System.out.println("Resuming Thread."); Thread.sleep(1000); ob1.mysuspend(); System.out.println("Stopping Thread."); ob1.mystop(); } catch(InterruptedException ex) {
Similar questions