How to create a thread in java? The following article will introduce to you 3 ways to create threads and their differences. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
If you want to create a thread in java, there are generally three methods:
1. Inherit the Thread class;
2. Implement the Runnable interface;
3. Use Callable and Future to create threads.
[Recommended learning: java video tutorial]
1. Inherit the Thread class
Inheritance For the Thread class, you must override the run method and define the tasks that need to be performed in the run method.
class MyThread extends Thread{ private static int num = 0; public MyThread(){ num++; } @Override public void run() { System.out.println("主动创建的第"+num+"个线程"); } }
After creating your own thread class, you can create a thread object, and then start the thread through the start() method. Note that the run() method is not called to start the thread. The run method only defines the tasks that need to be performed. If the run method is called, it is equivalent to executing the run method in the main thread. There is no difference from ordinary method calls. At this time, there is no A new thread will be created to perform the defined tasks.
public class Test { public static void main(String[] args) { MyThread thread = new MyThread(); thread.start(); } } class MyThread extends Thread{ private static int num = 0; public MyThread(){ num++; } @Override public void run() { System.out.println("主动创建的第"+num+"个线程"); } }
In the above code, by calling the start() method, a new thread will be created. In order to distinguish the difference between start() method call and run() method call, please look at the following example:
public class Test { public static void main(String[] args) { System.out.println("主线程ID:"+Thread.currentThread().getId()); MyThread thread1 = new MyThread("thread1"); thread1.start(); MyThread thread2 = new MyThread("thread2"); thread2.run(); } } class MyThread extends Thread{ private String name; public MyThread(String name){ this.name = name; } @Override public void run() { System.out.println("name:"+name+" 子线程ID:"+Thread.currentThread().getId()); } }
Run result:
From the output result The following conclusions can be drawn:
1) The thread IDs of thread1 and thread2 are different, and the ID of thread2 and the main thread are the same, indicating that calling the run method does not create a new thread, but runs directly in the main thread. The run method is no different from ordinary method calls;
2) Although the start method call of thread1 is called before the run method of thread2, the information related to the run method call of thread2 is output first, indicating that the new The process of thread creation will not block subsequent execution of the main thread.
2. Implement the Runnable interface
In addition to inheriting the Thread class when creating a thread in Java, you can also achieve something similar by implementing the Runnable interface function. Implementing the Runnable interface must override its run method.
The following is an example:
public class Test { public static void main(String[] args) { System.out.println("主线程ID:"+Thread.currentThread().getId()); MyRunnable runnable = new MyRunnable(); Thread thread = new Thread(runnable); thread.start(); } } class MyRunnable implements Runnable{ public MyRunnable() { } @Override public void run() { System.out.println("子线程ID:"+Thread.currentThread().getId()); } }
The Chinese meaning of Runnable is "task". As the name suggests, by implementing the Runnable interface, we define a subtask and then hand over the subtask to Thread for execution. . Note that this method must use Runnable as a parameter of the Thread class, and then use Thread's start method to create a new thread to perform the subtask. If you call Runnable's run method, no new thread will be created. This ordinary method call makes no difference.
In fact, if you look at the implementation source code of the Thread class, you will find that the Thread class implements the Runnable interface.
In Java, these two methods can be used to create threads to perform subtasks. Which method to choose depends on your own needs. Directly inheriting the Thread class may look simpler than implementing the Runnable interface, but since Java only allows single inheritance, if a custom class needs to inherit other classes, it can only choose to implement the Runnable interface.
3. Use Callable and Future to create threads
Unlike the Runnable interface, the Callable interface provides a call() method as a thread execution body, the call() method is more powerful than the run() method.
The steps to create and start a thread with a return value are as follows:
The following is an 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 ways to create threads:
The methods of implementing Runnable and Callable interfaces are basically the same, but the latter has a return value when executing the call() method. The run() method of the thread execution body has no 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. Threads only implement Runnable Or implement the Callable interface, and you can also inherit other classes.
2. In this way, multiple threads can share a target object, which is very suitable for situations where multiple threads process the same resource.
3. However, programming is slightly complicated. If you need to access the current thread, you must call the Thread.currentThread() method.
4. A thread class that inherits the Thread class cannot inherit from other parent classes (determined by Java single inheritance).
PS: It is generally recommended to create multi-threads by implementing interfaces
This article comes from the Java Introduction column, welcome to learn!
The above is the detailed content of 3 ways to create threads in Java and their differences. For more information, please follow other related articles on the PHP Chinese website!