Java re-learning-thread creation

Source: Internet
Author: User

Java creates threads in two ways, one inheriting the thread and the other implementing the runnable or callable interface.

One, Inherit thread

 Public classAPP { Public Static voidMain (string[] args) {thread thread=NewThread () {@Override Public voidrun () {inti = 0;  while(I < 100) {System.out.println (i++); Try{Thread.Sleep (1000); } Catch(interruptedexception e) {e.printstacktrace ();        }                }            }        };    Thread.Start (); }}

The example above is timed to output the value of I by overriding the thread's Run method, but the main thread of the Run method is only a normal method, you must call the Start method to create a thread to execute the Run method, call run directly without thread creation.

Second, implement the runnable or callable interface to create the thread.

The implementations of these two interfaces can only be turned into a normal class, and the threads to be created must be opened by other related classes.

The biggest difference between the two interfaces: the callable has a return value and can throw a detected exception, and runnable does not have a return value and cannot throw a detected exception;

1, for the Runnable interface,

  There are two ways to create a thread through it, one through thread, and the other through executor

 Public classAPP { Public Static voidMain (string[] args) {classMyrunnableImplementsRunnable {@Override Public voidrun () {System.out.println ("Start" +Thread.CurrentThread (). GetName ()); Try{Thread.Sleep (2000); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println ("End" +Thread.CurrentThread (). GetName ()); }} Thread Thread=NewThread (Newmyrunnable ());        Thread.Start (); Executor Executor=Executors.newsinglethreadexecutor (); Executor.execute (Newmyrunnable ()); }}

2, for the callable interface,

There are two ways to create a thread through it, one through thread, and the other through Executorservice, but all at the same time using the future interface to implement the control of the callable return value. Here the Executorservice interface is inherited executor interface, it adds some features, you can point to open source code to see and know, and the instantiation is through the Executors class static method to achieve.

2.1 Using Thread to create

Because thread can only accept runnable so to create callable thread through thread, but also to inherit the callable interface also inherits the Runnable interface class, this class is futuretask.

2.2 Through Executorservice to create

Since Executorservice naturally supports the callable interface, it is possible to submit directly.

 Public classAPP { Public Static voidMain (string[] args)throwsException {classMycallableImplementsCallable<integer>{@Override PublicInteger Call ()throwsException {thread.sleep (3000); System.out.println ("End"); return200; }} executorservice es=Executors.newcachedthreadpool (); Future<Integer> future = Es.submit (Newmycallable ()); System.out.println ("When Executorservice" +future.get ()); Futuretask<Integer> task =NewFuturetask<integer> (Newmycallable ()); Thread Thread=NewThread (Task);        Thread.Start (); System.out.println ("When Thread--" +task.get ()); }}

Note:

The Get method for the future is thread-blocking until the call () method of callable returns the value.

Remind the creation thread again not to call the Run method directly.

If you find that you can not understand, it is best to check the source.

Java re-learning-thread 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.