使用java的多线程概念控制运行Thread [英] Control of running Thread using multiple threading concept of java
问题描述
我只想在按下返回键时启动和停止线程。
这里线程停止正常,但我不能再次启动该线程请帮助。
还解释了我使用volatile关键字。这对我来说是有帮助的。
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();
}
}
输出
run:
press enter to stop
hello
hello
hello
hello
press enter to start
BUILD SUCCESSFUL (total time: 6 seconds)
推荐答案
线程不是可重入的,也就是说,一旦它们退出运行
方法,它们无法重新启动,需要创建新实例。
Thread's are not re-entrant, that is, once they exit the run
method, they can't be restarted, you need to create a new instance.
一个解决方案是创建 Sync
的新实例并启动它,但是一个更好的解决方案,基于您的代码可能是,使用等待
锁定以暂停线程并允许其恢复,例如......
One solution would be to create a new instance of Sync
and start it, but a better solution, based on you code might, be to use a wait
lock to "pause" the thread and the allow it to resume, for example...
public static class Sync implements Runnable {
private AtomicBoolean keepRunning = new AtomicBoolean(true);
private AtomicBoolean pause = new AtomicBoolean(false);
private ReentrantLock lckPause = new ReentrantLock();
private Condition conPause = lckPause.newCondition();
public void run() {
while (keepRunning.get() && !Thread.currentThread().isInterrupted()) {
while (pause.get() && !Thread.currentThread().isInterrupted()) {
lckPause.lock();
try {
System.out.println("Paused");
conPause.await();
} catch (InterruptedException ex) {
ex.printStackTrace();
} finally {
lckPause.unlock();
}
}
if (!Thread.currentThread().isInterrupted()) {
System.out.println("hello");
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
}
}
}
}
public void setPaused(boolean paused) {
if (pause.get() != paused) {
pause.set(paused);
if (!paused) {
lckPause.lock();
try {
conPause.signal();
} finally {
lckPause.unlock();
}
}
}
}
public void terminate() {
keepRunning.set(false);
setPaused(false);
}
}
这基本上设置了两个循环,一个让线程继续运行,直到它被终止,一个用于捕获暂停条件...
This basically sets up two loops, one to keep the thread running until it's "terminated" and one to trap the "pause" condition...
然后你可以做类似......
Then you could do something like...
public static void main(String[] args) {
Sync hi = new Sync();
Thread t = new Thread(hi);
t.start();
Scanner d = new Scanner(System.in);
System.out.println("press enter to pause");
d.nextLine();
hi.setPaused(true);
System.out.println("press enter to resume");
d.nextLine();
hi.setPaused(false);
System.out.println("press enter to terminate");
d.nextLine();
hi.terminate();
try {
t.join();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
System.out.println("Has terminated");
}
简单地运行它...
您应该注意,通常不鼓励直接从 Thread
扩展,并且通常鼓励使用单独的 Runnable
,有很多原因,但是你会发现将来最有用的一个原因是 Runnable
在API的不同部分得到更广泛的支持(比如执行者
API)使其成为一个更灵活的选择
You should note that it's generally discouraged to extend directly from Thread
and it is generally encouraged to use a separate Runnable
, there are many reasons, but one which you will find most useful in future is Runnable
is more widely supported in different parts of the API (like the Executors
API) making it a much more flexible option
看看 Concurrency Trail 了解更多详情,特别是锁定对象
Have a look at the Concurrency Trail for more details, in particular Lock Objects
这篇关于使用java的多线程概念控制运行Thread的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!