有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

多次使用java新线程

我想在按下按钮时运行线程

public void ButtonClick(){

    Thread thread = new Thread(){
        public void run(){
            Log.i("Test", "I'm in thread");
        }
    };
    thread.start();
}

我的问题是:我想在这个按钮上点击几次。打印“我在线程中”消息后是否仍存在多个线程?或者每次运行函数完成时,线程都会被销毁

如果我创建了几个同时运行的线程,如何以干净的方式关闭它们

谢谢你的帮助


共 (4) 个答案

  1. # 1 楼答案

    Are several thread still existing after the message "I'm in thread" is printed? Or each time the run function is finished, the thread is destroyed?

    在您的例子中,您正在创建许多线程,因为每次单击按钮都会创建一个线程

    run()方法中的最后一条语句完成后,线程的生命周期结束。在执行run()方法之后,线程将进入TERMINATEDState并且无法重新运行

    更好的解决方案不是每次点击按钮都创建一个新线程。如果应用程序中需要更多线程,请使用线程池

    Java为此提供了Executor框架。它以更好的方式管理线程生命周期

    使用其中一个API,它将从Executors返回ExecutorService

    例如newFixedThreadPool(4)

    查看此post和此article以了解更多选项

    In case I create several threads which are running at the same time, how can I close them in a clean way?

    您可以关闭ExecutorService,如下所述:

    How to properly shutdown java ExecutorService

    因为您使用的是Android,所以多线程还有一个很好的选择:HandlerThreadHandler

    有关更多详细信息,请参阅以下帖子:

    Android: Toast in a thread

  2. # 2 楼答案

    每次创建线程都是一个坏主意使用线程池

  3. # 3 楼答案

    Are several thread still existing after the message "I'm in thread" is printed?

    不会。每一个都会自动销毁

    In case I create several threads which are running at the same time, how can I close them in a clean way?

    无需停止线程,它们将在完成任务后自动销毁(执行运行

    要处理并发性和安全性,您应该查看^{},它是java中处理并发性的实用框架

  4. # 4 楼答案

    创建一个实现Runnable而不是匿名线程的类。。。传递可运行对象创建任意多的线程创建匿名可运行对象只创建一个对象,从而限制您实现需求。在创建另一个线程之前检查线程状态,或者使用并发创建线程组(已折旧)或线程池您可以使用callable而不是runnable,并将其传递给具有一定大小的线程池,或者您可以将runnable转换为callable,然后根据需要多次传递给线程池

    class Thop implements Runnable
     {
             public void run()
            {
                      // operation
             }
    }