Java thread comparison Thread, Runnable, Callable
java uses the Thread class to represent threads, and all field objects must be instances of the Thread class or its subclass. The function of each thread is to complete a certain task, which is actually to execute a program flow. Java uses thread execution bodies to represent this program flow.
1. Inherit the Thread class to create thread
The steps to start multithreading are as follows:
(1) Define the subclass of the Thread class and override the run() method of the class. The method body of the run() method represents the tasks that the class thread needs to complete. Therefore, the run() method is called the thread execution body.
(2) Create an instance of the Thread subclass, that is, create a thread object.
(3) Call the thread's star() method to start the thread.
The relevant codes are as follows:
/** * Inherit the inner class of thread to buy tickets for example*/ public class FirstThread extends Thread{ private int i; private int ticket = 10; @Override public void run() { for (;i<20;i++) { //When inheriting thread, use this directly to get the current thread, getName() Get the name of the current thread// Log.d(TAG,getName()+" "+i); if(this.ticket>0){ Log.e(TAG, getName() + ", ticket selling: ticket=" + ticket--); } } } } private void starTicketThread(){ Log.d(TAG,"starTicketThread, "+Thread.currentThread().getName()); FirstThread thread1 = new FirstThread(); FirstThread thread2 = new FirstThread(); FirstThread thread3 = new FirstThread(); thread1.start(); thread2.start(); thread3.start(); //Open 3 threads to buy tickets, each thread sold 10 tickets, and a total of 30 tickets}Running results:
You can see that the vote variables entered by 3 threads are not continuous. Note: ticket is an instance property of FirstThread, not a local variable, but because the program needs to create a FirstThread object every time it creates a thread object, all multiple threads do not share the attributes of the instance.
2. Implement the Runnable interface to create threads
Note: public class Thread implements Runnable
(1) Define the implementation class of the Runnable interface and override the run() method of the interface. The method body of the run() method is also the thread execution body of the thread.
(2) Create an instance of the Runnable instance class. This instance is used as a Thread target to create a Thread object. The Thread object is the real object.
The relevant codes are as follows:
/** * Implement the runnable interface and create a thread class */ public class SecondThread implements Runnable{ private int i; private int ticket = 100; @Override public void run() { for (;i<20;i++) { //If the thread class implements the runnable interface //Get the current thread, you can only use Thread.currentThread() to get the current thread name Log.d(TAG,Thread.currentThread().getName()+" "+i); if(this.ticket>0){ Log.e(TAG, Thread.currentThread().getName() + ", Ticket selling: ticket=" + ticket--); } } } } private void starTicketThread2(){ Log.d(TAG,"starTicketThread2, "+Thread.currentThread().getName()); SecondThread secondThread = new SecondThread(); //Create a new thread through new Thread(target,name) new Thread(secondThread,"Ticket buyer 1").start(); new Thread(secondThread,"Ticket buyer 2").start(); new Thread(secondThread,"Ticket Buyer 3").start(); //Although 3 threads were opened, only 100 tickets were bought in total}Running results:
You can see that the vote variables entered by 3 threads are continuous, and multiple threads can share the properties of the instance of the thread class using the Runnable interface. This is because in this way, the Runnable object created by the program is just a thread's target, and multiple threads can share the same target, so multiple threads can share the instance properties of the same thread class (which should actually be the target class of the thread).
3. Create threads using Callable and Future
Starting from Java 5, Java provides a Callable interface, which is an enhanced version of runnable. Callable provides a class called() method that can be used as a thread execution body, but the call() method is more powerful.
(1) The call() method can have a return value (2) The call() method can declare an exception thrown
Therefore, we can provide a callable object as the Thread target, and the executor of the thread is the call() method of the callable object. At the same time, java 5 provides the Future interface to represent the return value of the call() method in the Callable interface, and provides a futureTask implementation class. This implementation class implements the future interface and implements the runnable interface - a target that can be used as a Thread class.
The startup steps are as follows:
(1) Create an implementation class of the callable interface and implement the call() method. The call() method will be used as the execution body of the thread, and the call() method has a return value.
(2) Create an instance of the callable implementation class and use the FutureTask class to wrap the Callable object. The FutureTask object encapsulates the return value of the call() method.
(3) Create and start a new thread using the FutureTask object as the target of the Thread object.
(4) Call the get() method of the FutureTask object to get the return value after the child thread is executed.
The relevant codes are as follows:
/** * Use callable to implement thread class*/ public class ThirdThread implements Callable<Integer>{ private int ticket = 20; @Override public Integer call(){ for ( int i = 0;i<10;i++) { // Get the current thread, you can only use Thread.currentThread() to get the current thread name // Log.d(TAG,Thread.currentThread().getName()+" "+i); if(this.ticket>0){ Log.e(TAG, Thread.currentThread().getName() + ", Tickets: ticket=" + ticket--); } } return ticket; } } private void starCallableThread(){ ThirdThread thirdThread = new ThirdThread(); FutureTask<Integer> task = new FutureTask<Integer>(thirdThread); new Thread(task,"thread with return value").start(); try { Integer integer = task.get(); Log.d(TAG,"starCallableThread, the return value of the child thread="+integer); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } }Running results:
Note: Callable's call() method allows declarations to throw exceptions and allows for return values.
The program finally calls the get() method of the FutureTask object to return the return value of the Call() method, causing the main thread to be blocked until the call() method ends and returns.
4. Comparison of three ways
Create multi-threading by inheriting Thread class
Disadvantages: The Thread class has been inherited cannot be inherited from other parent classes.
Advantages: Simple to write
Create multi-threading using the method of inheriting Runnable and Callable interfaces
Disadvantages: Programming is a little complicated. If you need to access the current thread, you must use Thread.currentThread()
Advantages:
(1) It can also inherit other classes (2) Multiple threads can share a target object, so it is very suitable for multiple identical threads to handle the same resource, thereby separating CPU, code and data to form a clear model, which better reflects the object-oriented idea of class.
Thank you for reading, I hope it can help you. Thank you for your support for this site!