The three ways to create threads in Java are: 1. Inherit the Thread class to create a thread; 2. Implement the Runnable interface to create a thread; 3. Use Callable and Future to create a thread.
Java uses the Thread class to represent threads, and all thread objects must be instances of the Thread class or its subclasses. Java can create threads in three ways, as follows:
1) Inherit the Thread class to create threads
2) Implement the Runnable interface Create threads
3) Use Callable and Future to create threads
Let us look at these three methods of creating threads respectively.
------------------------Inherit the Thread class to create a thread------ ---------------
The general steps to create and start multi-threads by inheriting the Thread class are as follows
1]D define a subclass of the Thread class, and override the run() method of the class. The method body of this method is the task that the thread needs to complete, and the run() method is also Called the thread execution body.
#2] Create an instance of the Thread subclass, that is, create a thread object
3] Start the thread, that is, call the thread's start()Method
Code example
public class MyThread extends Thread{//继承Thread类 public void run(){ //重写run方法 } } public class Main { public static void main(String[] args){ new MyThread().start();//创建并启动线程 } }
------------------ ------Implement Runnable interface to create threads---------------------
By implementing Runnable The general steps for creating and starting a thread through an interface are as follows:
#1] Define the implementation class of the Runnable interface, and also override the run() method. This run() method is the same as the run() in Thread. ) method is also the execution body of the thread
#2] Create an instance of the Runnable implementation class, and use this instance as the target of Thread to create a Thread object. This Thread object is the real thread object.
3】The third part still starts the thread by calling the start() method of the thread object
Code example:
public class MyThread2 implements Runnable {//实现Runnable接口 public void run(){ //重写run方法 } } public class Main { public static void main(String[] args){ //创建并启动线程 MyThread2 myThread=new MyThread2(); Thread thread=new Thread(myThread); thread().start(); //或者 new Thread(new MyThread2()).start(); } }
------------------------Use Callable and Future to create threads------------- -------
is different from the Runnable interface. The Callable interface provides a call() method as the thread execution body. The call() method is The run() method must be powerful.
》The call() method can have a return value
》The call() method can declare that it throws an exception
Java5 provides the Future interface to represent the return value of the call() method in the Callable interface, and provides an implementation class FutureTask for the Future interface. This implementation class not only implements the Future interface, but also implements the Runnable interface, so Can be used as the target of the Thread class. Several public methods are defined in the Future interface to control its associated Callable tasks.
>boolean cancel(boolean mayInterruptIfRunning): View cancels the Callable task associated with the Future
>V get(): Returns the return value of the call() method in Callable, call this The method will cause the program to block, and the return value will not be obtained until the sub-thread ends.
>V get(long timeout, TimeUnit unit): Returns the return value of the call() method in Callable, blocking for up to timeout time , no return is thrown after the specified time. TimeoutException
>boolean isDone(): If the Callable task is completed, it returns True
>boolean isCancelled(): If it is canceled before the Callable task is completed normally. Cancel, return True
After introducing related concepts, the steps to create and start a thread with a return value are as follows:
1】Create an implementation class of the Callable interface and implement call () method, and then create an instance of the implementation class (starting from java8, you can directly use Lambda expressions to create Callable objects).
2] Use the FutureTask class to wrap the Callable object. The FutureTask object encapsulates the return value of the call() method of the Callable object.
3 】Use the FutureTask object as the target of the Thread object to create and start the thread (because FutureTask implements the Runnable interface)
#4】Call the get() method of the FutureTask object to obtain the result after the execution of the sub-thread. Return value
Code example:
public class Main { public static void main(String[] args){ MyThread3 th=new MyThread3(); //使用Lambda表达式创建Callable对象 //使用FutureTask类来包装Callable对象 FutureTask<Integer> future=new FutureTask<Integer>( (Callable<Integer>)()->{ return 5; } ); new Thread(task,"有返回值的线程").start();//实质上还是以Callable对象来创建并启动线程 try{ System.out.println("子线程的返回值:"+future.get());//get()方法会阻塞,直到子线程执行结束才返回 }catch(Exception e){ ex.printStackTrace(); } } }
------------------------ -------------Comparison of three methods of creating threads---------------------------------- -------
The ways to implement Runnable and the Callable interface are basically the same, except that the latter has a return value when executing the call() method, and the latter has no return value when the thread execution body run() method Return value, so these two methods can be classified into one. The difference between this method and the method inheriting the Thread class is as follows:
1. Потоки реализуют только интерфейс Runnable или Callable, а также могут наследовать другие классы.
2. Таким образом, несколько потоков могут совместно использовать целевой объект, что очень удобно для ситуаций, когда несколько потоков обрабатывают один и тот же ресурс.
3. Однако программирование немного сложное. Если вам нужно получить доступ к текущему потоку, вы должны вызвать метод Thread.currentThread().
4. Класс потока, который наследует класс Thread, не может наследовать от других родительских классов (определяется единым наследованием Java).
Примечание. Обычно рекомендуется создавать многопотоки путем реализации интерфейсов.
Для получения дополнительной информации о программировании посетите: Видеокурс по программированию! !
The above is the detailed content of What are the three ways to create threads in java?. For more information, please follow other related articles on the PHP Chinese website!