有什么方法可以停止使用布尔值实现Runnable的线程,而不扩展Thread?

时间:2015-08-30 19:35:11

标签: java multithreading

考虑代码:

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?

4 个答案:

答案 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