I just want to start and stop the thread when return key is pressed. Here thread is stopped fine but i cant Start that thread again please help. Also explain me the use of volatile keyword .Is it helpful for me to over come this problem.
public class Sync extends Thread{
public boolean meth= true;
public void run(){
while(meth){
System.out.println("hello");
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
}
}
}
public void shutdown(){
meth=false;
}
public void startup(){
meth=true;
}
}
MAIN CLASS``
package com.Sync;
import java.util.Scanner;
public class SyncMain {
public static void main(String[] arg) throws InterruptedException{
Sync hi= new Sync();
hi.start();
System.out.println("press enter to stop");
Scanner d= new Scanner(System.in);
d.nextLine();
hi.shutdown();
System.out.println("press enter to start");
d.nextLine();
hi.startup();
}
}
OUTPUT
run:
press enter to stop
hello
hello
hello
hello
press enter to start
BUILD SUCCESSFUL (total time: 6 seconds)