Java Thread Series (i) Threading creation

Source: Internet
Author: User

Java Thread Series (i) Threading creation

There are three main ways to create threads in Java: Inherit thread, implement Runnable interface, use Executorservice, callable, and future to implement multithreading by returning results.

First, inherit the thread class to create a threading class
publicclassextends Thread {     publicvoidrun() {         for (int010000; i++) {             System.out.println("线程一" + i);         }     }       publicstaticvoidmain(String[] args) {          newMyThread();          th.start();     }  }  

Note: The run () method that is called directly by the start () method to start the thread is only an ordinary method.

Second, implement Runnable interface create thread
 Public classMyrunnableImplementsRunnable { PublicString ThreadName; Public myrunnable(String tname)      {threadname = Tname; } Public void Run() { for(inti =0; I <10000; i++) {System. out.println(ThreadName); }      } Public Static void Main(string[] args) {Myrunnable Th1 =New myrunnable("Thread A"); Myrunnable Th2 =New myrunnable("Thread B"); Thread myth1 =NewThread (Th1); Thread myth2 =NewThread (Th2); Myth1.Start(); Myth2.Start(); }  }

Summary: Using the Runnable interface to create a thread has two deficiencies, one is unable to synchronously return the results of the execution of the thread, and the second is that the run () method cannot throw an exception. The following describes the callable interface to solve this problem.

Third, the use of executorservice, callable, future implementation by the return result of multithreading
/** * Thread with return value */  @SuppressWarnings("Unchecked")classTest { Public Static void Main(string[] args)throwsExecutionexception, interruptedexception {System. out.println("----program starts running----"); Date date1 =NewDate ();intTasksize =5;//Create a thread poolExecutorservice pool = executors.Newfixedthreadpool(tasksize);//Create multiple tasks with return valueslist<future> list =NewArraylist<future> (); for(inti =0; i < tasksize; i++) {Callable c =New mycallable(i +" ");//Perform tasks and get future objectsFuture F = pool.Submit(c);//System.out.println (">>>" + f.get (). toString ()); List.Add(f); }//close thread poolPool.shutdown();//Get running results for all concurrent tasks         for(Future F:list) {//Get the return value of the task from the future object and output it to the consoleSystem. out.println(">>>"+ F.Get().toString()); }    }  }classMycallableImplementscallable<object> {PrivateString Tasknum;mycallable(String tasknum) { This.Tasknum= Tasknum; } PublicObjectPager()throwsException {Thread.Sleep( +);returnTasknum; }  }

"40 Java Multithreading problem Summary": http://www.importnew.com/18459.html

Record a little bit every day. Content may not be important, but habits are important!

Java Thread Series (i) Threading creation

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.