Java Core Learning (21) Multithreading---Three ways to create a startup thread

Source: Internet
Author: User
Tags custom name

This section begins the Java Multithreaded Programming learning, the basic concepts of the operating system, processes, threads are no longer mentioned, just understand Java for multithreaded programming support.

First, inherit the thread class to create threads

The Java language uses the thread class to represent threads, and classes that represent threads can implement multithreaded development by inheriting the thread class and overriding the run () method, invoking the Start method of the thread class instance to start the thread. Here's a try.

 

 Packagethreadtest; Public classFirstthreadextendsthread{Private inti;  Public voidrun () { for(; i<100;i++) {System.out.println (GetName ()+ " "+i); }    }     Public Static voidMain (string[] args) { for(inti = 0; i<10000; i++){            //Thread.CurrentThread () method to get the current thread instanceSystem.out.println (Thread.CurrentThread (). GetName () + "" +i); if(i = = 20){                NewFirstthread (). Start (); NewFirstthread (). Start (); }        }    }}

The output is conceivable, with three threads running alternately. Where the Mian thread is the father thread of Thread-0 and Thread-1, multiple threads cannot share instance variables of the thread class when creating a thread using the thread class that inherits the thread class.

Second, implement the Runnable interface to create the threading class

There is only one abstract method in the Runnable interface, void Run (), which is a function-type interface. If you open the code for the thread class, you can see that the thread class also implements the Runnable interface.

The class that implements the run () method of the Runnable interface can only count as a target, just provides the run method for the thread, and to really create the thread must call the thread's construction method to create the thread, but it also uses thread to create it.

Here's a try.

 Packagethreadtest; Public classSecondthreadImplementsrunnable{Private inti;  Public voidrun () { for(; i<100;i++) {System.out.println (Thread.CurrentThread (). GetName ()+ " " +i); }    }     Public Static voidMain (string[] args) { for(inti = 0;i<100;i++) {System.out.println (Thread.CurrentThread (). GetName ()+ " "+i); if(i==20) {Runnable St=NewSecondthread (); NewThread (St, "Custom name"). Start (); }        }    }}

  

This is the thread's Run method, and you can see that the thread called the Run method of the Runnable implementation class.

Iii. creating threads using callable and future

Callable interface has only a call () abstract method, unlike run (), call () has a return value that can throw an exception

Is the callable interface definition

  

Generic v represents the return value type of the call method

So how to get the call method of the class that implements the callable interface as the thread execution body, how to obtain the return value of the call method?

This requires that the Future,future interface represents the return value of the call () method, the return value that the Get method of the calling future instance can go to, corresponds to the callable interface, and the future also supports generics.

Also need to use the Futuretask class, this class implements the future interface and runnable, can get the return value, also can be created as a thread target

Futuretask's constructor

Futuretask's Run method

Let's use it.

 Packagethreadtest;Importjava.util.concurrent.Callable;Importjava.util.concurrent.Future;ImportJava.util.concurrent.FutureTask; Public classthirdthread{ Public Static voidMain (string[] args) {Thirdthread TT=NewThirdthread (); Futuretask<Integer> task =NewFuturetask<integer> (NewCallable<integer>() {@Override PublicInteger Call ()throwsException {intI =0;  for(; i<100;i++) {System.out.println (Thread.CurrentThread (). GetName ()+ " " +i); }                returni;        }        });  for(inti = 0;i<100;i++) {System.out.println (Thread.CurrentThread (). GetName ()+" "+i); if(i = = 20){                NewThread (task, "Thread with return value"). Start (); }            Try{System.out.println ("Child thread Return value:" +task.get ()); }Catch(Exception ex) {ex.printstacktrace (); }        }    }}

Note here that when you call the Get method of the Futuretask method, the current thread is blocked before it gets the return value.

You typically use the latter two ways to create a thread

Java Core Learning (21) Multithreading---Three ways to create a startup thread

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.