Several implementations of Java multi-threading record

Source: Internet
Author: User

The traditional way of implementing threads is three, inheriting the thread class, overriding the run () method, implementing the Runable interface, overriding the run () method, implementing the callable interface, overriding the call () method, and documenting the most basic three encoding implementations.

First, Inherit thread

Class Extendsthread  extends thread{    void run () {System.out.println ("Hello Thread"void newNew extendsthread (); Et1.start (); Et2.start ();}}       

Second, realize runnable interface

PublicClass Implementsrunableimplements Runnable { public void Run () {System.out.println ("Hello Thread");} public static void main (string[] args) {implementsrunable ir1 = new implementsrunable (); Implementsrunable Ir2 = new implementsrunable (); new Thread (IR1). Start (); new Thread (IR2). Start ();}}               

Third, realize callable interface

 Public classImplementscallableImplementsCallable {Private intID;  PublicImplementscallable (intID) {         This. ID =ID; }     PublicString Call ()throwsException {return"This Thread Id is:" + This. GetId (); }     Public intgetId () {returnID; }     Public voidSetId (intID) { This. ID =ID; }     Public Static voidMain (string[] args)throwsexecutionexception, interruptedexception {executorservice es=Executors.newcachedthreadpool (); List<Future<String>> results =NewArrayList ();  for(inti=1;i<=10;i++) {Results.add (Es.submit (Newimplementscallable (i))); } thread.sleep (10000);  for(future<string>fs:results) {            if(Fs.isdone ()) {System.out.println (Fs.get ()); } Else{System.out.println ("The Thread isn't down yet");    }} es.shutdown (); }}

Note: the Execute () method of Executorservice does not return a value, and the Submit () method has a return value of type future<t>.

Several implementations of Java multi-threading record

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.