Java multithreaded Programming--thread creation method

Source: Internet
Author: User

In Java, there are several ways to create threads:

By implementing the Runnable interface;

By inheriting the Thread class itself;

Create threads through callable and Future.

to create a thread by implementing the Runnable interface

The easiest way to create a thread is to implement the Runnable interface directly, which defines a run () method that defines our own tasks in our implementation class by implementing the implementation of the method, which enables us to perform our own tasks after creating and starting threads. For example, if we are going to perform a countdown task, we can do it like the following code:

public class Runnabledemo implements Runnable {
    @Override public
    void Run () {
        System.out.println ("Countdown started:") ;
        for (int i = 0; i < i++) {
            System.out.println (10-i);
            try {
                thread.sleep (1000);
            } catch (Interruptedexception e) {
                e.printstacktrace ();
            }

    }} public static void Main (string[] args) {
        thread thread = new Thread (new Runnabledemo (), "Runnable-thread");

        Thread.Start ();
    }

to create a thread by inheriting thread

The second way to create a thread is to create a new class that inherits the thread class (we'll elaborate on the thread class in a subsequent article), and then create an instance of the class.
An inheriting class must override the run () method, which is the entry point for the new thread. It must also call the start () method to execute.
Although the method is listed as a multithreaded implementation, it is essentially an example of a Runnable interface.
Overriding the above countdown task through inheritance thread is as follows:

public class Threaddemo extends Thread {public

    void run () {
        System.out.println ("Countdown started:");
        for (int i = 0; i < i++) {
            System.out.println (10-i);
            try {
                thread.sleep (1000);
            } catch (Interruptedexception e) {
                e.printstacktrace ();
            }

    }} public static void Main (string[] args) {
        Threaddemo thread = new Threaddemo ();

        Thread.Start ();
    }

creating threads through callable and Future

Runnable is the independent task of performing work, but he does not return any value, if you want the task to return a value when completed, you can implement the callable interface. The callable interface is a generic interface with a type parameter, and by looking at its source we can see that its type parameter represents the type of the value returned from call (). Callable types of tasks can be performed in two ways:

Using Futuretask to execute

To carry out the operation with the help of executor

Using Futuretask to execute

Create the implementation class for the callable interface and implement the call () method, which acts as a thread execution body and has a return value.

Creates an instance of the callable implementation class, using the Futuretask class to wrap the callable object, which encapsulates the return value of the call () method for the callable object.

Creates and starts a new thread using the Futuretask object as target of the thread object.

Call the Get () method of the Futuretask object to obtain the return value after the child thread execution ends.

public class Callablethreaddemo implements callable<integer> {
    @Override public
    Integer call () throws Exception {
        System.out.println ("Thread is in the calculation");
        Thread.Sleep (1000);
        int sum = 0;
        for (int i=0;i<100;i++)
            sum = i;
        return sum;
    }

    public static void Main (string[] args) throws Interruptedexception, executionexception {
        callable<integer> Mycallabletask = new Callablethreaddemo ();  

        futuretask<integer> futuretask= New futuretask<integer> (mycallabletask);  

        New Thread (Futuretask). Start ();

        System.out.println ("Return Value:" +futuretask.get ());
    }
}

To carry out the operation with the help of executor

The executor must be invoked using the Executorservice.submit () method, and the following is a modification of the previous instance:

public class CallableThreadDemo2 implements callable<integer> {

    @Override public
    Integer call () throws Exception {
        System.out.println ("Thread is in the calculation");
        Thread.Sleep (1000);
        int sum = 0;
        for (int i=0;i<100;i++)
            sum = i;
        return sum;
    }

    public static void Main (string[] args) throws Interruptedexception, executionexception {
        executorservice exec = exec Utors.newcachedthreadpool ();

        future<integer> Future = exec.submit (New CallableThreadDemo2 ());

        System.out.println ("return value:" + future.get ());

        Exec.shutdown ();
    }

three different ways to compare

When creating multiple threads in a way that implements Runnable, callable interfaces, the thread class simply implements the Runnable interface or the callable interface, and can also inherit other classes.

When creating multiple threads using the inheritance thread class, writing is simple, and if you need to access the current thread, you can get the current thread without using the Thread.CurrentThread () method, using this directly.

Reference:
http://www.runoob.com/java/java-multithreading.html
Java programming Ideas

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.