我如何创建新线程来执行某些任务并在任务完成后停止线程

时间:2019-12-13 13:23:20

标签: java multithreading threadpool

它似乎是一个愚蠢的问题,但是我试图在一个新线程中创建一个任务,并且在任务完成之后,该线程应该退出而无需调用任何命令将其从main停止。

这里是一个例子:


public class Main {

    public static void main(String[] args) {
    // write your code here
        foo f1= new foo();
        Thread t= new Thread(f1);
        f1.doSomething();
    }
}
class foo extends Thread{

    void doSomething(){
        // download File for example
    }
} 

如果我实现这样的run方法:

class foo extends Thread{

    void doSomething(){
        // download File for example
    }
    void run(){
      doSomething();
    }
} 

它将永远调用doSomething()方法。

2 个答案:

答案 0 :(得分:0)

这是一种解决方案:

public class ThreadExample extends Thread {

     private void doSomething(){
          System.out.println("Inside : doSomething()");
     }  

    @Override
    public void run() {
        System.out.println("Inside : " + Thread.currentThread().getName());
        doSomething();
    }

    public static void main(String[] args) {
        System.out.println("Inside : " + Thread.currentThread().getName());

        System.out.println("Creating thread...");
        Thread thread = new ThreadExample ();

        System.out.println("Starting thread...");
        thread.start();
    }

}
  

一个输出:

     

内部:主要
  正在创建线程...
  启动线程...
  内部:螺纹-0
  内部:doSomething()

有关更多信息,请查看此Java Concurrency and Multithreading tutorial

答案 1 :(得分:0)

std::unique_ptr

这不是启动线程的捷径。基本上,您调用thread.start()方法来启动线程,该线程将执行run方法中存在的所有内容。

请先阅读本教程

https://docs.oracle.com/javase/tutorial/essential/concurrency/index.html

https://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html

相关问题