考虑代码:
public class MyThread implements Runnable{
private volatile static boolean running = true;
public void stopThread()
{
running = false;
}
@Override
public void run() {
while (running)
{
try {
System.out.println("Sleeping ...");
Thread.sleep(15000);
System.out.println("Done sleeping ...");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args)
{
MyThread thread = new MyThread();
thread.run();
}
}
是否可以使用布尔值停止实现Runnable的线程,而不扩展Thread?
答案 0 :(得分:1)
是否可以停止实现Runnable的线程
实现Runnable
的类不是线程。它只是一个没有魔力的普通类,声明了一个void run()
方法。因此,您的示例不会启动任何线程。
因此,您应该将其命名为MyThread
而将传递给MyTask
构造函数,而不是误导性地命名您的类Thread
:
final MyTask task = new MyTask();
new Thread(task).start();
Thread.sleep(2000);
task.stopRunning(); // renamed from stopThread
另外,请将运行标志设为实例变量。每个MyTask
都应该有自己的运行标志。
答案 1 :(得分:0)
MyThread myt = new MyThread();
(new Thread(myt)).start();
稍后致电
myt.stopThread();
答案 2 :(得分:0)
听起来你想要使用built in interrupt mechanism,这与你试图实现的基本相同。
public class MyRunnable implements Runnable{
@Override
public void run() {
while (!Thread.interrupted())
{
try {
System.out.println("Sleeping ...");
Thread.sleep(15000);
System.out.println("Done sleeping ...");
} catch (InterruptedException e) {
// This means someone called thread.interrupt() while you were sleeping
return;
}
}
}
public static void main(String[] args)
{
// You didn't extend Thread, you implemented Runnable:
Thread thread = new Thread(new MyRunnable());
// thread.run() is synchronous, for this (the main) thread to continue use:
thread.start();
...
thread.interrupt();
}
}
答案 3 :(得分:0)
是的,你可以。您上面的Runnable
代码几乎是正确的,但您可能应该使running
字段不是静态的。但是,创建Thread
的方式需要额外的步骤。它应该是:
Runnable r = new MyThread(); // MyThread already implements Runnable instead of extending Thread, so that's correct.
Thread t = new Thread(r);
t.start(); // not t.run() or r.run(), that would execute the code synchronously
r.stopThread(); // when needed