JAVA implements three methods of threading

  • 2020-04-01 02:21:21
  • OfStack

(1) inherit the Thread class and override the run function
Create:
The class xx extends Thread {
  Public void the run () {
Thread.sleep(1000) // the Thread sleeps for 1000 milliseconds, and sleep causes the Thread to enter the Block state and free the resource
}}
Start thread:
Object. Start () // starts the thread and the run function runs
(2) implement the Runnable interface and override the run function
Start thread:
Thread t = new Thread(object) // create a Thread object
T.s tart ()
(3) implement the Callable interface and rewrite the call function
Callable is an interface similar to Runnable, and the classes that implement the Callable interface and the classes that implement Runnable are tasks that can be performed by other threads.
There are several differences between Callable and Runnable:
The method specified by Callable is call(), while the method specified by Runnable is run().
The Callable task returns a value, while the Runnable task does not
The call() method can throw an exception, but the run() method cannot.
Run the Callable task to get a Future object, which represents the result of the asynchronous calculation. It provides a way to check if the computation is complete, etc
The Future object can be used to understand the execution of the task, cancel the execution of the task, and obtain the result of the task execution

Related articles: