Create threads in java to run in background

后端 未结 3 1391
误落风尘
误落风尘 2020-11-30 01:57

I want to spawn a Java thread from my main java program and that thread should execute separately without interfering with the main program. Here is how it should be:

<
相关标签:
3条回答
  • 2020-11-30 02:24

    And if you like to do it the Java 8 way, you can do it as simple as this:

    public class Java8Thread {
    
        public static void main(String[] args) {
            System.out.println("Main thread");
            new Thread(this::myBackgroundTask).start();
        }
    
        private void myBackgroundTask() {
            System.out.println("Inner Thread");
        }
    }
    
    0 讨论(0)
  • 2020-11-30 02:27

    One straight-forward way is to manually spawn the thread yourself:

    public static void main(String[] args) {
    
         Runnable r = new Runnable() {
             public void run() {
                 runYourBackgroundTaskHere();
             }
         };
    
         new Thread(r).start();
         //this line will execute immediately, not waiting for your task to complete
    }
    

    Alternatively, if you need to spawn more than one thread or need to do it repeatedly, you can use the higher level concurrent API and an executor service:

    public static void main(String[] args) {
    
         Runnable r = new Runnable() {
             public void run() {
                 runYourBackgroundTaskHere();
             }
         };
    
         ExecutorService executor = Executors.newCachedThreadPool();
         executor.submit(r);
         // this line will execute immediately, not waiting for your task to complete
         executor.shutDown(); // tell executor no more work is coming
         // this line will also execute without waiting for the task to finish
        }
    
    0 讨论(0)
  • 2020-11-30 02:32

    This is another way of creating a thread using an anonymous inner class.

        public class AnonThread {
            public static void main(String[] args) {
                System.out.println("Main thread");
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                    System.out.println("Inner Thread");
                    }
                }).start();
            }
        }
    
    0 讨论(0)
提交回复
热议问题