Java multithreaded Learning (ii)

Source: Internet
Author: User

Define a task that produces a return value

In an introduction to the previous article, we learned that the usual way to define a task is to define a class that implements the Runnable interface, which is a task for us. It is also easy to note, however, that the most important method of a task is the run () method, and the run () method does not return a value , meaning that the task we defined earlier does not return any values.

If you want to define a task that has a return value, you need to write a class that implements the callable interface . Callable is a generic type parameter, whose type parameter represents the return value type of the call () method.

Examples are as follows:

1 Importjava.util.concurrent.Callable;2 Importjava.util.concurrent.ExecutionException;3 ImportJava.util.concurrent.ExecutorService;4 Importjava.util.concurrent.Executors;5 Importjava.util.concurrent.Future;6 7 /**8  * @authorGao9 * date:2016.5Ten  * */ One  A classTaskImplementsCallable<string> { -     intTestnum; -      PublicTask (inttestnum) { the          This. Testnum =Testnum; -     } -      PublicString Call () { -         return"Test number is" +Testnum; +     } - } +  A  Public classReturneddemo { at      Public Static voidMain (string[] args) { -         //creates an instantiated object of Executorservice, which is used to perform tasks.  -Executorservice exec =Executors.newcachedthreadpool (); -future<string> future = Exec.submit (NewTask (123)); -         Try { -              in System.out.println (Future.get ()); -}Catch(interruptedexception e) { to             //TODO Auto-generated catch block + e.printstacktrace (); -}Catch(executionexception e) { the             //TODO Auto-generated catch block * e.printstacktrace (); $         }Panax Notoginseng          -     } the } + /*Output: A Test number is 123 the */

You may not understand the meaning of future<t> in the example code above. The instantiated object of the Executorservice class returns the return value of the future<t> type when the Submit () method is called, and the future object that we instantiate here is used to hold the return value, which is then used for processing and other procedures. At the same time, an exception is generated when the get () method is called, so the segment is surrounded with try-catch blocks.

Ii. priority and concession of threads 1. Thread Priority

Threads are called by the thread scheduler, and thread schedulers tend to let the higher priority threads run first. However, because the order of the CPU processing thread sets is not fixed, the thread scheduler only acts as a "recommendation" rather than a decisive one. At the same time, the thread priority simply represents the frequency of thread execution in the thread set. High-priority threads execute at a higher frequency, but low-priority threads are also executed.

Because different operating systems have different priorities and differ from the JDK's priority (JDK has 10 priority), the mapping of JDK and operating system priorities is not very good. Usually when we adjust the priority, we use only max_priority, norm_priority, min_priority three levels.

The sample code is as follows:

1 ImportJava.util.concurrent.ExecutorService;2 Importjava.util.concurrent.Executors;3 4 /**5  * @authorGao6 * date:2016.57  * */8 classPrioritytaskImplementsRunnable {9     intPriority ;Ten      PublicPrioritytask (intPriority ) { One          This. Priority =Priority ; A     } - @Override -      Public voidrun () { the Thread.CurrentThread (). SetPriority (priority); -System.out.println ( This); -     } -      PublicString toString () { +         returnThread.CurrentThread () + ";"; -     } + } A  Public classPrioritytest { at      Public Static voidMain (string[] args) { -Executorservice exec =Executors.newcachedthreadpool (); -          for(inti = 0; I < 5; i++)  -Exec.execute (NewPrioritytask (thread.max_priority)); -Exec.execute (NewPrioritytask (thread.min_priority)); - Exec.shutdown (); in          -     } to }     + /*Output: - Thread[pool-1-thread-3,10,main]; the Thread[pool-1-thread-4,10,main]; * Thread[pool-1-thread-1,10,main]; $ Thread[pool-1-thread-5,10,main];Panax Notoginseng Thread[pool-1-thread-2,10,main]; - Thread[pool-1-thread-6,1,main]; the  + */

In this example, we define the thread by setting a different priority for the thread, and its priority is displayed in the threads ' information.

2. Concession of threads

In the introduction to the first article, we applied the Thread.yield () method in the example, and this method shows the threading concession. Usually we execute this method after the execution of the other method body of the run () method, which is intended to send a signal to the thread scheduler that the thread scheduler has basically done its job and can allocate the CPU to other threads for use. However, as described in the above thread precedence, because the order in which the CPU processes the existing set of threads is indeterminate, the yield () method only gives the scheduler a recommendation, not the actual execution of the yield () method to divide the CPU to other threads that require the CPU at the same level.

3. Background Threads

(1) Background thread definition: A background thread is a thread that provides a generic service in the background while the program is running.

This thread is generally not part of the program's indispensable parts.

(2) Background thread settings: Use the thread object to call the Setdaemon () method, which can be set as a background thread.

Note: You must set it before the thread is started before it can be set as a background thread successfully.

Third, thread-related exception issues

If you mention an exception, you will not feel unfamiliar. For multithreaded programming, if you do not take steps to catch these exceptions, the run () method of the task is propagated out to the console as soon as the exception is escaped.

Currently in order to solve the problem of thread exception capture, we can modify the way executor generates threads. The implementation is based on the interface provided by Java: Thread.uncaughtexceptionhandler. This interface allows programmers to attach an exception handler on each thread object that is written.

PS: There are examples of anomalies that will be introduced and explained in the next Article blog post.

Java multithreaded Learning (ii)

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.