Javase Review _10 Multithreading review

Source: Internet
Author: User

the difference between wait () and sleep (): 1.wait (): There is no wait time, while sleep () requires a wait time as a parameter. 2. There is a difference between the execution of the CPU and the handling of locks in synchronization: wait () releases execution and locks. You need to re-compete the lock after waking up . Sleep (): Release execution and do not release lock
void Show () {     Synchronized (this) {          wait ()          /// can have three threads waiting at the same time. Only after you get the lock can you continue to run down }}void  start () {     notifyall     (); // after waking up, three threads are eligible for execution, but not all of them have executive power. }
Interupt: You can force a thread to be enforced from a frozen state through interrupt, but an exception will occur that needs to be handled. When a thread calls the interrupt method, the interrupt state of the thread is set. This is the Boolean flag that each thread has, and each thread can check the flag to see if the current thread is interrupted (judging by the isinterrupted method). If the thread is blocked , (such as wait and sleep threads), at which point the interrupt method is called and the blocking call is interrupted by an interruptedexception exception. If you call the Sleep method when you break the state, you will not hibernate, but will clear the interrupt state and throw a interruptedexception exception.An example:
 Public classinterrupted { Public Static voidMain (string[] args) {Task T=NewTask (); Thread T1=NewThread (t);    T1.start (); }}classTaskImplementsRunnable {@Override Public voidrun () { for(inti=0;i<50;i++) {            if(i==30) Thread.CurrentThread (). interrupt (); System.out.println (Thread.CurrentThread (). isinterrupted ()+""+i); }    }}

Output:

False0false1false2false3false4false5false6false7false8false9false10false11false12false13false14false15false16false17false 18false19false20false21false22false23false24false25false26false27false28false29true30true31true32true33true34true35true36 True37true38true39true40true41true42true43true44true45true46true47true48true49
Setdaemon: Sets the thread to be the daemon thread (background thread), at which time the daemon will stop running when the virtual machine is left with only the daemon thread running. Join: Calling the Join method for a thread causes the Current ThreadThe execution is temporarily released, and the thread will not run until the thread that is requested to join has finished executing. SetPriority: Sets the priority of the thread public static void Yield (): comity the thread, yielding the CPU's execution. If there are other running threads that have at least the same high priority as this thread, Then these threads will then be dispatched lock.newcondition: A conditional variable will be obtained, and a lock can have one or more related conditional objects. Await method that places the thread in the waiting set of the condition, The Signalall method will release the blocking state of all the localities in the waiting set for that condition. The Notifyall,wait,notify method can only be used in synchronous methods and synchronous code blocks volatile is a lock-free mechanism for instance domain synchronization, and if you declare a domain to be volatile, the compiler and virtual machine know that the domain is likely to be updated concurrently by another thread. Therefore, the update operation of the variable can immediately notify the other thread, and the new value can be immediately synchronized to the main memory.You can build your own instance of each thread through the Threadlocal helper class: You can use the following code:
 Public Static Final threadlocal<simpledateforamt> dateformat=New threadlocal<simpledateforamt>() {      protected SimpleDateFormat InitialValue () {          returnnew SimpleDateFormat ("Yyyy-mm-dd"  );     }}
The InitialValue method is dropped when the Get method is first called in a given thread, after which the Get method returns an instance of the current thread. to determine if there is a thread-safe problem, be sure to look at two points: first, there is no shared by all the operation of the field data, second, the operation will not create a security riskWhen a thread calls the lock () method to attempt to acquire a lock, it is possible to block, the Trylock method attempts to request a lock, returns true if the lock is successfully obtained, or returns false immediately, and the current thread can leave immediately to do other things.  Boolean Trylock (Long time,timeunit Unit): attempts to acquire a lock, the blocking time does not exceed the given value if True is returned successfully. The await method can also provide parameters, await (long time,timeunit unit): If time expires, then unblock Java.util.concurrent.locks defines another lock, read-write lock, You can obtain read locks that can be shared by multiple read threads (but exclude write operations). And excludes write locks for all other operations. The method is as follows:
Private Reentrantreadwritelock rwl=New  reentrantreadwritelock (); Private Lock readlock=rwl.readlock ();          // read operation sharing, rejecting write operations Private Lock Writelock=rwl.writelock ();        // Repel all other operations
Stop method is stopped using because there is no way to know when to call the Stop method is safe and when to cause the object to be corrupted. When you want to stop a thread, the thread that is interrupted will stop when it is safe. (judged by ininterrupted).Callerable is similar to runnable, but the internal method has a return value. The type parameter is the type of the return value. The future can save the results of an asynchronous calculation, The Futuretask Wrapper is a convenient mechanism for converting callable to future and runnable, which simultaneously implements both interfacesFor example
Importjava.util.concurrent.Callable;Importjava.util.concurrent.ExecutionException;ImportJava.util.concurrent.FutureTask;/*** Created by Administrator on 2016/6/30.*/ Public classExercise { Public Static voidMain (string[] args) {Futuretask<Integer> task=NewFuturetask<integer> (NewCounter ());//Packaging CallableThread t=NewThread (Task);  T.start (); //This is the feature of the Runnable interface        Try{System.out.println (Task.get ()); //This is the feature of the Future interface}Catch(interruptedexception e) {e.printstacktrace (); } Catch(executionexception e) {e.printstacktrace (); }    }}classCounterImplementsCallable<integer> {    intsum; @Override PublicInteger Call ()throwsException { for(inti=0;i<100;i++) {sum+=i; }        returnsum; }}
Executorservice Newcashedthreadpool (): Returns a thread pool with a cache that creates threads when necessary. Executorservice newfixedthreadpool (int threads): Returns a thread pool in which the number of threads in the pool is specified by the parameter, and threads that exceed the parameters are placed in the processing queue. Executorservice newsinglethreadexecutor (): Returns an executor that executes individual tasks sequentially in one and a single thread. The thread pool can invoke the task that the submit submission needs to perform, A future object is returned. Can be used to cancel an object. If the thread pool submits a task that is a callable type, the task can take advantage of the returned future object to call the Get method to get the value. What to do when using the connection pool: 1) Call the static method Newcachedthreadpool or Newfixedthreadpool in the Executors class. 2) Call submit to submit runnable and callable objects 3) If you want to cancel a task or want to get the value of the callable object, save the returned future object. 4) Call shutdown If you are no longer submitting any tasks. Simple example:   
 //  public static Executorservice Newfixedt Hreadpool (int nthreads)  Executorservice pool = executors.newfixedthreadpool (2)        ;          //  can execute runnable object or the thread represented by callable object         Future Fu1=pool.submit (new   myrunnable ()); Future FU2  =pool.submit (new   Mycallable (        )); Fu1.cancel ();  //         Cancel the task  System.out.println (Fu2.get ()); //  //  end thread pool  pool.shutdown (); 

Javase Review _10 Multithreading review

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.