【发布时间】:2015-07-30 05:44:27
【问题描述】:
我只想在按下返回键时启动和停止线程。 这里线程停止正常但我无法再次启动该线程请帮助。 还要解释一下volatile关键字的使用。对我克服这个问题有帮助吗?
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;
}
}
主类``
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();
}
}
输出
run:
press enter to stop
hello
hello
hello
hello
press enter to start
BUILD SUCCESSFUL (total time: 6 seconds)
【问题讨论】:
-
(stackoverflow.com/questions/106591/…) 了解有关 volatile 的更多信息
标签: java multithreading volatile