How to start anonymous thread class

前端 未结 8 762
清歌不尽
清歌不尽 2020-12-04 15:37

I have the following code snippet:

public class A {
    public static void main(String[] arg) {
        new Thread() {
            public void run() {
               


        
8条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-04 15:56

    I'm surprised that I didn't see any mention of Java's Executor framework for this question's answers. One of the main selling points of the Executor framework is so that you don't have do deal with low level threads. Instead, you're dealing with the higher level of abstraction of ExecutorServices. So, instead of manually starting a thread, just execute the executor that wraps a Runnable. Using the single thread executor, the Runnable instance you create will internally be wrapped and executed as a thread.

    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    // ...
    
    ExecutorService threadExecutor = Executors.newSingleThreadExecutor();
    try {
      threadExecutor.execute(
        new Runnable() {
          @Override
          public void run() {
            System.out.println("blah");
          }
        }
      );
    } finally {
        threadExecutor.shutdownNow();
    }
    

    For convenience, see the code on JDoodle.

提交回复
热议问题