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