. Several ways to implement multithreading

Source: Internet
Author: User


There are three kinds:
(1) Inheriting the thread class, overriding the Run function
Create:

[Java] View plain copy

<span style= "FONT-SIZE:12PX;" >class XX extends thread{
public void Run () {
Thread.Sleep (1000)//thread sleeps for 1000 milliseconds, sleep causes the thread to enter the block state, and frees the resource
}}</span>



To open a thread:
Object. Start ()//start thread, run function
(2) Implementing the Runnable interface, overriding the Run function
To open a thread:

[Java] View plain copy

<span style= "FONT-SIZE:12PX;" > Thread t = new Thread (object)//Create thread object
T.start () </span>



(3) Implement callable interface, rewrite call function

Callable are similar to runnable interfaces, classes that implement callable interfaces, and classes that implement runnable, are tasks that can be performed by other threads.


There are several differences between callable and runnable:


The method prescribed by ①callable is call (), and the method specified by runnable is run ().
②callable can return a value after a task is executed, and Runnable's task cannot return a value.
The ③call () method throws an exception, and the run () method cannot throw an exception.
④ run the callable task to get a future object that represents the result of an asynchronous calculation. It provides a way to check whether a calculation is completed,

The calculation is completed and the results of the calculation are retrieved. The future object allows you to understand task execution, cancel task execution, and get the results of task execution



Java Callable code Example:


[HTML] View plain copy

Class Taskwithresult implements Callable<string> {
private int id;

public taskwithresult (int id) {
This.id = ID;
}

@Override
Public String Call () throws Exception {
Return "result of Taskwithresult" + ID;
}
}

public class Callabletest {
public static void Main (string[] args) throws Interruptedexception,
executionexception {
Executorservice exec = Executors.newcachedthreadpool ();
arraylist<future<string>> results = new arraylist<future<string>> (); The future is equivalent to a container for storing the results of executor execution.
for (int i = 0; i < i++) {
Results.add (Exec.submit (New Taskwithresult (i)));
}
for (future<string> fs:results) {
if (Fs.isdone ()) {
System.out.println (Fs.get ());
} else {
System.out.println ("Future result was not yet complete");
}
}
Exec.shutdown ();
}
}

Operation Result:

Result of Taskwithresult 0
Result of Taskwithresult 1
Result of Taskwithresult 2
Result of Taskwithresult 3
Result of Taskwithresult 4
Result of Taskwithresult 5
Result of Taskwithresult 6
Result of Taskwithresult 7
Result of Taskwithresult 8
Result of Taskwithresult 9







Blog Park
Home
New Essays
Contact
Management
Subscription
Subscription

Essays-309 Articles-0 comments-5
Four ways to implement Java multithreading

There are four main ways to implement Java Multithreading: Inheriting the Thread class, implementing the Runnable interface, implementing the callable interface through Futuretask wrapper to create thread threads, using Executorservice, callable, Future implementations have multiple threads that return results.

The first two methods have no return value after the thread has finished executing, and the latter two are with the return value.



1. Inherit the thread class to create threads
The thread class essentially implements an instance of the Runnable interface, representing an instance of a thread. The only way to start a thread is through the start () instance method of the thread class. The start () method is a native method that starts a new thread and executes the run () method. This way of implementing multithreading is simple, by extend thread directly through your own class, and by copying the run () method, you can start a new thread and execute your own defined run () method. For example:
Copy Code

public class MyThread extends Thread {
public void Run () {
System.out.println ("Mythread.run ()");
}
}

MyThread myThread1 = new MyThread ();
MyThread myThread2 = new MyThread ();
Mythread1.start ();
Mythread2.start ();

Copy Code

2. Implement runnable Interface Creation thread
If your class already extends another class, you cannot directly extends the Thread, at which point you can implement a runnable interface, as follows:

In order to start mythread, you need to instantiate a thread first and pass in your own Mythread instance:

In fact, when a runnable target parameter is passed to thread, the thread's Run () method calls Target.run (), referencing the JDK source code:

3. Implement the callable interface to create thread threads through the Futuretask wrapper

The callable interface (and only one method) is defined as follows:

Public interface Callable<v> {
V call () throws Exception; }

Copy Code

public class Somecallable<v> extends Otherclass implements callable<v> {

@Override
Public V Call () throws Exception {
TODO auto-generated Method Stub
return null;
}

}

Copy Code
Copy Code

callable<v> onecallable = new somecallable<v> ();
Create a Futuretask<integer> object from callable<integer>:
futuretask<v> OneTask = new futuretask<v> (onecallable);
Note:futuretask<integer> is a wrapper that is created by accepting Callable<integer>, which implements both the future and the Runnable interface.
Create a thread object from futuretask<integer>:
Thread onethread = new Thread (onetask);
Onethread.start ();
At this point, a thread is created.

Copy Code

4. Use Executorservice, callable, and future to implement threads with return results

The Executorservice, callable, and future three interfaces are actually executor frameworks. The thread that returns the result is a new feature introduced in the JDK1.5, and with this feature it is no longer necessary to get the return value. And it can be flawed if it is achieved.

A task that can return a value must implement the callable interface. Similarly, a task without a return value must implement the Runnable interface.

After performing the callable task, you can get a future object that is called get on the object to get to the object returned by the callable task.

Note: The Get method is blocked, that is, the thread has no return result, and the Get method waits.

Combined with the thread pool interface, Executorservice can realize the multi-threading of the legendary return results.

Here is a complete example of a multithreaded test with return results, which can be used directly under JDK1.5. The code is as follows:
Copy Code

Import java.util.concurrent.*;
Import Java.util.Date;
Import java.util.List;
Import java.util.ArrayList;

/**
* Thread with return value
*/
@SuppressWarnings ("Unchecked")
public class Test {
public static void Main (string[] args) throws Executionexception,
interruptedexception {
SYSTEM.OUT.PRINTLN ("----program starts running----");
Date date1 = new Date ();

int tasksize = 5;
Create a pool of threads
Executorservice pool = Executors.newfixedthreadpool (tasksize);
Create multiple tasks with return values
list<future> list = new arraylist<future> ();
for (int i = 0; i < tasksize; i++) {
Callable C = new Mycallable (i + "");
Perform tasks and get future objects
Future F = Pool.submit (c);
System.out.println (">>>" + f.get (). toString ());
List.add (f);
}
Close the thread pool
Pool.shutdown ();

Get run results for all concurrent tasks
for (f:list) {
Gets the return value of the task from the future object and outputs it to the console
System.out.println (">>>" + f.get (). toString ());
}

Date Date2 = new Date ();
SYSTEM.OUT.PRINTLN ("----program ends running----, program run Time" "
+ (Date2.gettime ()-date1.gettime ()) + "millisecond" ");
}
}

Class Mycallable implements Callable<object> {
Private String Tasknum;

Mycallable (String tasknum) {
This.tasknum = Tasknum;
}

Public Object Call () throws Exception {
System.out.println (">>>" + tasknum + "task start");
Date DATETMP1 = new Date ();
Thread.Sleep (1000);
Date DATETMP2 = new Date ();
Long time = Datetmp2.gettime ()-datetmp1.gettime ();
System.out.println (">>>" + tasknum + "task termination");
return tasknum + "task returns run result, current task time" "+" "+" "milliseconds";
}
}

Copy Code



Code Description:
The executors class in the code above provides a series of factory methods for creating a thread pool, and the returned thread pool implements the Executorservice interface.
public static Executorservice newfixedthreadpool (int nthreads)
Creates a thread pool of a fixed number of threads.
public static Executorservice Newcachedthreadpool ()
Creates a cacheable thread pool that calls execute to reuse previously constructed threads if the threads are available. If an existing thread is not available, a new thread is created and added to the pool. Terminates and removes from the cache those threads that have not been used for 60 seconds.
public static Executorservice Newsinglethreadexecutor ()
Create a single-threaded executor.
public static Scheduledexecutorservice newscheduledthreadpool (int corepoolsize)
Create a thread pool that supports timed and recurring task executions, which in most cases can be used to replace the timer class.

Executoreservice provides the submit () method, passing a callable, or runnable, back to the future. If the executor background thread pool has not completed the calculation of callable, this call returns the Get () method of the future object, blocking until the calculation is complete.


. Several ways to implement multithreading

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.