Java Multithreading--< eight > Multithreading other concepts

Source: Internet
Author: User

I. Overview

To the eighth quarter, the basic concept of multithreading is finished. Add all the previous articles to this link:

Java Multithreading--< > overview, defining Tasks

Java Multithreading--< two > Assign tasks to threads, thread declaration and startup

Java Multithreading--< three > Simple thread execution: Executor

Java Multithreading--< four > Let line threads return value

Java multithreaded--< five > Background thread (daemon)

Java multithreaded--< six > more convenient threading

Java Multithreading--< seven > Multi-threading Exception snapping

are personal understanding and summary, the code is from the "Thinking in Java", there are questions welcome to correct.

Second, the other concept of multithreading

1. Hibernation

Hibernation, in fact, is to let the thread pause for some time, that is, blocking for some time. For example, after each print, each thread is going to sleep (that is, blocking), which allows the thread scheduler to switch to another thread to drive another task. This causes the threads to be guaranteed in the execution order, which can be verified by viewing the printout message.

 Public classTasksleepingtaskextendstask{@Override Public voidrun () {Try{             while(countdown--> 0) {System.out.println (status ()); /** After each print, each thread sleeps (that is, blocking), which allows the thread scheduler to switch to another thread to drive another task*/TimeUnit.MICROSECONDS.sleep (100000); }            /** Because exceptions cannot be passed back to main across threads, you must handle the exception online thread*/        }Catch(interruptedexception e) {System.out.println (); }    }     Public Static voidMain (string[] args) {Executorservice exec=Executors.newcachedthreadpool ();  for(inti = 0; I < 5; i++) {Exec.execute (NewTasksleepingtask ());    } exec.shutdown (); }}

However, this does not mean that you can hibernate to ensure that the execution order of the task (the sequential behavior depends on the underlying threading mechanism, which differs between different operating systems

To control the order of the solution: 1, synchronization control, 2, the collaboration thread (and then do the ordinal)

2. Priority level

The priority represents the importance of the thread, and the thread scheduler tends to allow the higher priority thread to execute first (but this does not mean that a lower priority thread will not be executed, i.e. priority will not cause a deadlock). A lower priority thread is simply a low-frequency execution, and in most of the time all threads should run at the default priority, and attempting to manipulate the thread priority is usually a mistake.

Use the Thread.CurrentThread () method to obtain a reference to the thread object that drives the task, and then set the thread priority.

 Public classTaskpriorityImplementsrunnable{Private intCountdown = 5; /** Variable d is used to ensure that no compiler optimizations are made*/@SuppressWarnings ("Unused")    Private volatile DoubleD//No optimization    Private intPriority ;  PublicTaskpriority (intPriority ) {         This. Priority =Priority ; }    /** The name of the print thread, the priority of the thread, and the thread group that the thread belongs to, inside the threads, to obtain a reference to the thread object that drives the task by calling Thread.CurrentThread ()*/     PublicString toString () {returnThread.CurrentThread () + ":" +Countdown; } @Override Public voidrun () {/** Priority should be set at the beginning of run, and setting them in the constructor will not do any good because executor has not started to perform the task at the moment .*/Thread.CurrentThread (). SetPriority (priority); /** Performed 10,000 floating-point arithmetic, the mathematical operation can be interrupted, where the operation time is long enough, * so the thread scheduling mechanism is too late to intervene, exchange tasks and focus on priority, so that the highest priority of the thread is the preferred choice*/         while(true){             for(inti = 1; i < 10000;i++) {D+ = (Math.PI + MATH.E)/(Double) I; if(i%1000==0) Thread.yield (); System.out.println ( This); if(--countdown = = 0 )                     return; }        }    }     Public Static voidMain (string[] args) {Executorservice exec=Executors.newcachedthreadpool ();  for(inti = 0; I < 5;i++) {Exec.execute (NewTaskpriority (thread.min_priority));//1} exec.execute (NewTaskpriority (thread.max_priority));//TenExec.shutdown (); }}

Although the JDK has 10 priorities, it does not map well with most operating systems (Windows7, SOLARIS2), and the only portable method is to try max_priority/norm_priority/min_ when adjusting the priority. Priority three types of statements

3. Concession

You can give a hint to the thread scheduling mechanism when you have confirmed that you have completed the work required during an iteration of the Run method's loop: Your work is almost done, allowing other threads to try out the CPU. (Allow other threads of the same priority to run).

Java provides the call yield () method to implement. It is only implied that there is no mechanism to guarantee that it will be adopted, so it cannot be relied upon. As in the above example.

Java Multithreading--< eight > Multithreading other concepts

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.