Three ways of thread creation-java

First of all, we must distinguish the difference between threads and processes in Java:
1. The smallest unit of system allocation of resources during a process, and a thread is the smallest unit of system scheduling.
2. A process contains multiple threads.

Multi-threaded usage scenarios:
1. Mainly to improve performance and efficiency.
2. When blocking code causes subsequent code to fail to execute, use multithreading.

There are three ways to create threads in Java concurrent programming:

Method 1: Use the Thread() class to create a thread;

Use the Thread class to create a thread, and rewrite the run () method, call the start () method to start the thread. After calling the start method, the thread is not executed immediately, but is in the ready state. This ready state means that the thread has already obtained other resources except for the CPU resources. It will be in the running state after waiting for the CPU resources to be allocated. CPU resources are allocated This process is done for us by the operating system . Once the run method is completed, the thread becomes a terminated state.

public class ThreadTest {
    
    
    public static class MyThread extends Thread{
    
    
        @Override
        public void run() {
    
    
            System.out.println("start");
            //使用this来获取当前线程
            System.out.println(this);
        }
    }
    public static void main(String[] args) {
    
    
        //创建线程
        MyThread thread=new MyThread();
        //启动线程
        thread.start();
        System.out.println("end");

    }
}

Insert picture description here

Method 2: Inherit the Runnable() interface;

Create a RunnableTask class to implement the Runnable interface and implement the run() method.

class RunnableTask implements Runnable{
    
    
    @Override
    public void run() {
    
    
        System.out.println("start");
    }
}
public class RunnableTest {
    
    
    public static void main(String[] args) {
    
    
        RunnableTask task=new RunnableTask();
        new Thread(task).start();
        new Thread(task).start();
        System.out.println("88");
    }
}

Method 3: Use the Callable() interface;

The CallerTask class implements the call() method of the Callable interface, and creates a FutureTask object in the main function, then uses the created FutureTask object as a task to create a thread and start it, and finally waits for the task to complete and return through futureTask.get() result.

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

class CallerTask implements Callable<String>{
    
    

     @Override
     public String  call() throws Exception {
    
    
         return "hello";
     }
 }
public class CallableTest {
    
    
    public static void main(String[] args) {
    
    
        //创建异步任务
        FutureTask<String> futureTask=new FutureTask<>(new CallerTask());
        //启动线程
        new Thread(futureTask).start();
        System.out.println("girl");
        try{
    
    
            //等待任务执行完毕,并返回结果
            String result=futureTask.get();
            System.out.println(result);

        }catch (ExecutionException | InterruptedException exc){
    
    
            exc.printStackTrace();
        }


    }
}

to sum up:

1. Advantages of using Thread to create a thread :
Get the current thread in the run method and use this directly, without using the Thread.currentThread() method;
Disadvantages:
Java does not support multiple inheritance. If you inherit the Thread class, you can no longer inherit Other classes.
There is no separation of tasks and code.

2. The advantages of using the Runnable interface to create threads :
tasks and codes are separated, and multiple threads can perform the same task without requiring multiple copies of code.
Multiple classes can be inherited using the Runnable interface.
Disadvantage: The
task has no return value.

3. Advantages of the Callable interface:
FutureTask can be used to receive the return value of the thread. Support multiple inheritance.
Disadvantages: To return to the current thread, you must call Thread.currentThread(), not this.

Guess you like

Origin blog.csdn.net/m0_46551861/article/details/115104478