There are many ways to create multithreading in Java, here's a quick comb
1. Inheriting the thread class
Inherit the Java.lang.Thread class, create a local multithreaded class, overload the Run () method, and invoke the thread's method to start the threads. The sample code is as follows:
Mythread.java
PublicClassMyThreadExtendsThread {PublicvoidRun () {Privateint copy =0; System.out.println ("Thread ID:" + thread.currentthread (). GetName () +"= = Print Time:" + system.currenttimemillis ()); System.out.println ("Thread serialnum:" + ++copy); try {sleep (1000);} catch (Interruptedexception e) {e.printstacktrace ();} System.out.println ("Thread ID:" + thread.currentthread (). GetName () +"= = Print Time:" + System.currenttimemillis ()); } public static void main (string[] args) {MyThread MT1 = new MyThread (); MyThread mt2 = new MyThread (); MyThread mt3 = new MyThread (); System.out.println ("Start all Threads:"); Mt1.start (); Mt2.start (); Mt3.start (); }}
Output Result:
Start all Threads:Thread id:Thread-0 == print time:1495975884383Thread serialnum:1Thread id:Thread-1 == print time:1495975884383Thread serialnum:1Thread id:Thread-2 == print time:1495975884383Thread serialnum:1Thread id:Thread-1 == print time:1495975885385Thread id:Thread-0 == print time:1495975885385Thread id:Thread-2 == print time:1495975885385
2. Implement the Runnable interface
Implement the Run method of the Java.lang.Runnable interface, instantiate the thread class with the implemented object, and invoke the Start () method of the Thread object.
Example code:
PublicClassMyrunnableImplementsRunnable {Privateint copy =0;PublicvoidRun () {System.out.println ("Thread ID:" + thread.currentthread (). GetName () +"= = Print Time:" + system.currenttimemillis ()); System.out.println ("Thread serialnum:" + ++copy); try {sleep (1000);} catch (Interruptedexception e) {e.printstacktrace ();} System.out.println ("Thread ID:" + thread.currentthread (). GetName () +"= = Print Time:" + System.currenttimemillis ()); } public static void main (string[] args) {myrunnable Mr = New myrunnable (); System.out.println ("Start all Threads:"); New Thread (MR). Start (); New Thread (MR). Start (); New Thread (MR). Start ();}}
Output Result:
start all Threads:thread Id:Thread-0 = = Print Time:1495975833588thread id:thread- 1 = = Print Time:1495975833588thread Serial: 1thread id:thread-2 = = Print Time: 1495975833588Thread serial:2thread serial:3thread id:thread-< Span class= "Hljs-number" >0 = = Print Time:1495975834603thread id:thread-1 = = Print Time:1495975834603thread id:thread-2 = = Print Time:1495975834603
Comparing the thread method with the Runnable method makes the output less difficult to find:
. Both can achieve multithreading concurrency effect
. The Runnable method can use a Runnable object to create multiple threads, which share the resources of their dependent runnable objects, for scenarios where multiple threads handle the same resource (online for more examples: Sell tickets); The thread method is completely independent of each other's threads
In fact, too expensive, the current runnable use more than the thread method is more common, in addition to the above-mentioned reasons for resource sharing, Java's single inheritance has increased the limitations of the thread method.
3. Implement the Callable interface
Compared with the method of inheriting the thread class and implementing the method of Runnable interface, the method of implementing callable interface can not only realize multithreading concurrency, but also can handle the return value of thread or get execution exception. Using callable for multithreaded programming requires implementing the callable call method (specifying the return value, throwing an exception in the calls method), constructing the Futuretask object associated with it, and after starting the thread, the results of the thread execution are stored in the Futuretask object. can be obtained using Futuretask's Get method. Example code:
Import java.util.concurrent.Callable;Import Java.util.concurrent.FutureTask;ImportStatic java.lang.Thread.sleep;PublicClassMycallableImplementscallable<integer> {Privateint flag =0;Public IntegerCall ()Throws Exception {System.out.println ("Thread ID:" + thread.currentthread (). GetName () +"= = Print Time:" +system.currenttimemillis ()); Sleep10000); System.out.println ("Thread ID:" + thread.currentthread (). GetName () +"= = Print Time:" +system.currenttimemillis ()); ++flag;return flag; }PublicStaticvoid main (string[] args) throws exception{mycallable mycallable = new mycallable (); futuretask<integer> future = new futuretask<integer> (myCallable); futuretask<integer> future2 = new futuretask<integer> (myCallable); new Thread (Future). Start (); new Thread (Future2). Start (); int result,result2; //while (!future.isdone ()); Result = Future.get (); ////while (!future2.isdone ()); RESULT2 = Future2.get (); System.out.println ( "GET THREAD NAME:" + Result); System.out.println ( "GET THREAD NAME 2:" +RESULT2);}}
Execution Result:
Thread id:Thread-0 == print time:1495997744617Thread id:Thread-1 == print time:1495997744617Thread id:Thread-0 == print time:1495997754625Thread id:Thread-1 == print time:1495997754625GET THREAD NAME:1GET THREAD NAME 2:2
The code execution logic above is similar to the example code in the previous runnale by constructing a thread object to start multithreading. The difference is that the Futuretask method is constructed here to store the thread return value. It is important to note that the type in the callable generic interface of the thread and the return value type of the call () method are consistent with the generic interface type of the Futuretask.
4. Using the thread pool and executor framework
In the previous three scenarios, we created the task of runnable or callable or thread, throwing it into thread to start, we need to manually manage various multi-threaded parameters, such as the number of threads, thread reuse, thread safety control and so on. The JAVA5 later version provides executor technology that provides a well-established thread pool that provides a complete solution for multithreading, an effective way to manage the number of threads, thread reuse policies, secure threads, and avoid this escaping problem.
The thread pooling scenarios provided by Executor include Newcachedthreadpool,newfixedthreadpool,newscheduledthreadpool and Singlethreadexecutor (Fork/ The join framework also provides a newworkstealingpool, which provides different thread management scenarios, and executes a Executorservice object that can call the Execute () method or the Submit () method, Submit the previously defined runnable task or callable task or thread task to each thread to execute
As an example of the more commonly used Newcachedthreadpool (), the following example code uses Executorservice to perform a callable object task to get the return value for each thread.
Import java.util.ArrayList;Import java.util.List;Import java.util.concurrent.*;ImportStatic java.lang.Thread.sleep;PublicClassMyCallable2Implementscallable<string> {Public StringCall ()Throws exception{Sleep (1000); System.out.println ("Terminate the Thread:" +thread.currentthread (). GetName ());Return Thread.CurrentThread (). GetName (); }PublicStaticvoidmain (string[] args) {Executorservice es = Executors.newcachedthreadpool (); list<future<string>> futurelist = new arraylist<future<string>> (); for (int i=0;i<5;i++" {Future future = Es.submit (new MyCallable2 ()), Futurelist.add (future) ; } for (future f:futurelist) {while (!f.isdone ()); try {System.out.println (" EXECUTE RESULT: "+f.get ());} catch (interruptedexception e) {e.printstacktrace ();} catch (executionexception e) {e.printstacktrace ();} finally {Es.shutdown ();}} }}
The results of the implementation are as follows:
Terminate the thread:pool-1-thread-5terminate the thread:pool- 1-thread-4terminate the thread:pool- 1-thread-3terminate the thread:pool- 1-thread-2terminate the thread:pool- 1-thread-1execute result:pool-1- Thread-1execute result:pool-1-thread- 2execute result:pool-1-thread- 3EXECUTE result:pool-1-thread-4execute RESULT:pool-1-thread-5
Creating a runnable thread with executors is similar to creating a callable thread without managing the return value, which is relatively straightforward and is not mentioned here.
Java multithreading creates-thread,runnable,callable and ThreadPool