Java Multithreading comprehension and implementation method

Source: Internet
Author: User

1. By inheriting the thread class, overwrite the run method to implement multithreading.

1  Public classMytest {2      Public Static voidMain (string[] args) {3Thread MyThread1 =NewMyThread1 ();4Thread myThread2 =NewMyThread1 ();5         //call the Start method6 Mythread1.start ();7 Mythread2.start ();8         //call the Run method9         //Mythread1.run ();Ten         //Mythread2.run (); One     } A } -  - classMyThread1extendsThread { the      Public voidrun () { -          for(inti=0; i<10; i++){ - System.out.println (i); -             Try { +Thread.Sleep (10); -}Catch(interruptedexception e) { +                 //TODO auto-generated Catch block A e.printstacktrace (); at             } -         } -          -     } -}

The start () method should be called to start a thread so that the thread is in a ready state, and the thread class calls the run () method to execute it, so that the code above will alternately execute the output.

If you use the run () method directly, it simply invokes a method, which is executed sequentially in the main thread, so the code above will be output sequentially.

2. Realize multithreading by implementing the Runnable interface. (In fact, the Thread class also implements the Runable interface, public class Thread extends Object implements Runnable)

1  Public classMytest2 {2      Public Static voidMain (string[] args) {3MyThread2 Mythread =NewMyThread2 ();4Thread Thread1 =NewThread (mythread);5Thread thread2 =NewThread (mythread);6         //execute the Start method7 Thread1.start ();8 Thread2.start ();9         //execute the Run methodTen         //Thread1.run (); One         //Thread2.run (); A     } -  - } the  - classMyThread2ImplementsRunnable { - @Override -      Public voidrun () { +          for(inti=0; i<10; i++){ - System.out.println (i); +             Try { AThread.Sleep (10); at}Catch(interruptedexception e) { -                 //TODO auto-generated Catch block - e.printstacktrace (); -             }             -         } -          in     } -      to}

Because the implementation of the Runable subclass does not have a start () method, it is implemented through the public thread of the thread class (Runnable target) construction method.

In the actual project, because Java can only inherit a single class, can implement a multi-interface, so often with the inherited Runable interface to implement multithreading.

There is also an important difference between inheriting the thread class and implementing the Runable interface, which can easily realize the sharing of resources. The latter can be passed

MyThread2 mythread = new MyThread2 ();
Thread thread1 = new Thread (mythread);
Thread thread2 = new Thread (mythread);

Let Thread1 and Thread2 share the resources, because they preach the same mythread.

3. Use the executor framework to implement multithreading.

Why use the executor framework?

The executor framework makes it easy to implement multi-threading with returned results, both of which have no return value.

1  Public classMytest3 {2      Public Static voidMain (string[] args) {3         //set the number of threads4         intThreadsize = Runtime.getruntime (). Availableprocessors ();5         //get a thread pool with a fixed number of threads through executors6Executorservice ThreadPool =Executors.newfixedthreadpool (threadsize);7         //used to store returned results8List<future> flist =NewArraylist<future>();9         //submit task to thread poolTen          for(inti=0; i<10; i++){ OneFuture F = Threadpool.submit (NewCallFunction (i, "my thread" +i)); A Flist.add (f); -         } - Threadpool.shutdown (); the         //gets the returned result -          for(Future f:flist) { -             Try { - System.out.println (F.get (). toString ()); +}Catch(interruptedexception e) { -                 //TODO auto-generated Catch block + e.printstacktrace (); A}Catch(executionexception e) { at                 //TODO auto-generated Catch block - e.printstacktrace (); -             } -         } -     } -  in } - classCallFunctionImplementsCallable<object> { to     //Thread ID +     Private inttaskId; -     //Thread Content the     PrivateString taskcontent; *      $CallFunction (inttaskId, String taskcontent) {Panax Notoginseng          This. TaskId =taskId; -          This. taskcontent =taskcontent; the     } +      A     //methods that are called by each thread the @Override +      PublicObject Call ()throwsException { -String result = TaskId + ":" +taskcontent; $         returnresult; $     }   -      -}

The above code is mainly designed to Executorservice, CallFunction, future.

Executorservice is primarily obtained by executors.newfixedthreadpool a fixed thread pool.

CallFunction is the implementation of the callable interface, unlike the Runable interface, callable can return a value, and runable cannot return a value

The future is used to receive the return value, which is a multi-threaded parallel commit when it is submitted, and when using the Get method of the future, it will be serially waiting for the thread to execute until the result is returned.

Java Multithreading comprehension and implementation method

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.