Java------Multithreading (enhanced)

Source: Internet
Author: User
Tags thread class time in milliseconds

strengthen the article 1. Thread Mutex lock

A, multi-threaded mutex shared "Basic data type Data" resource, the lock (with the Synchronized keyword) must be an object, the basic data type of the variable can not be used as an object lock, at the same time, to ensure that multi-threaded use is the same mutex (object lock), in order to synchronize.

b, multi-threaded mutex shared "stack" resource

Example: Multi-Window ticket

Package thread.ticket.v1;          public class Sellingtickets {public static void main (string[] args) {window r1=new window ("Windows 1");          Thread t1=new thread (r1);                    T1.start ();          Window r2=new windows ("2");          Thread t2=new thread (R2);                    T2.start ();          Window r3=new windows ("3");          Thread T3=new thread (r3);                    T3.start ();          Window r4=new windows ("4");          Thread t4=new thread (R4);      T4.start ();      }} class Window implements runnable{private static int num=200;            Because a resource of the base data type cannot be used as an object lock, and it is a static member of the class,//So you can create a new object that is parallel to the shared "basic data Type" resource, instead of it to do the object lock private static Object Obj=new object ();            Private String Windowname=null;      Public Window (String windowname) {this.windowname = Windowname; } @Override public void Run () {///synchronized (obj) {//) If the lock is added here, it will become a window. All the tickets are sold out, and if not added, it will be All the windows are sold together,//and rarely outExisting duplicate tickets, but as the software is not safe to do so, because running on other machines is likely to have a duplicate ticket phenomenon,//So should be like the following to put the lock in the while to go while (true) { You cannot use this to replace the obj synchronized (obj) {///sync block---The basic data type of the variable cannot be used as a mutex.                      Because the mutex is an object lock if (num > 0) {System.out.println (Windowname + ":" + num--);                      } else {break;   }                  }              }  //      }      }  }
2. Multi-Thread scheduling

Multithreading in Java is a preemptive way of running (a thread that starts first is more likely to preempt a resource)

1) setpriority () method: Set Priority

As long as a thread before the start of this method call for him can increase the probability of preemption to the resource, the default is 5, the smaller the ability to seize resources

< Span style= "font-size:14px" >2) The Sleep () method and the Interrupt () method: The Sleep () method of the thread class is a static method for the current thread operation, and does not release the object lock when the sleep () method is executed. The parameters for sleep () specify the thread sleep time in milliseconds. The thread does not resume execution until this time, unless the execution is resumed early because of an outage. You can use interrupt () to prematurely interrupt the sleep () method, or you can break it by throwing an exception. One thread can invoke the interrupt () method of another thread, which emits a interruptedexception to the suspended thread. The ability to wake up a suspended thread in disguise. The method of the thread class, interrupt (), is a forced wake-up technique.

Package thread.schedule.v1;          public class Schedule {public static void main (string[] args) {Thread t1=new MyThread ();            Thread t2=new MyThread ();          T1.start ();                    T2.start ();              try {thread.sleep (2000);          T1.interrupt ();//forced wakeup of T1 thread after two seconds} catch (Interruptedexception e) {e.printstacktrace ();      }}}} class MyThread extends thread{private static Object Obj=new object ();              @Override public void Run () {synchronized (obj) {try {thread.sleep (5000);              } catch (Interruptedexception e) {System.out.println (This.getname () + "has been awakened"); } for (int i = 1; i <=; i++) {System.out.println (Thread.CurrentThread (). GetName () +              "--no--" + i);   }          }      }    }
3) Yield () method: Used to enable threads with the same priority to get the chance to execute. If other threads with the same priority are operational, yield () places the thread in a running pool and runs the other thread. If there are no running threads of the same priority, nothing is done.

Note: Once the yield () method is executed, the thread simply discards the current opportunity and then re-grabs the CPU with the other threads, possibly enters upgradeable than the other lines.

Package cn.hncu.thread.schedule.v2;          public class Schedule {public static void main (string[] args) {Thread t1=new MyThread ("T1");            Thread t2=new MyThread ("T2");  T1.start ();          try {//T1.join ();//If a join () is used here, the yield () method is not shown//} catch (Interruptedexception e) {//  E.printstacktrace ();          } System.out.println ("Main .....");                T2.start ();      }} class MyThread extends thread{private static Object Obj=new object ();            Private String Threadname=null;      Public MyThread (String threadname) {this.threadname = ThreadName; } @Override public void Run () {///synchronized (obj) {System.out.println (":::::::::" + th              Readname);              int num = 0; while (This.threadName.equals ("T1") && num++ <) {This.yield ()//yield does not release the object lock, so even if the SY is wrapped around the perimeter Nchronized also cannot make the thread discard, until the thread has finished executing, and when no lock is usedThis yield () method words each time the T1 thread to give up, but he will again and T2 thread Rob resources} for (int i = 1; i <=; i++) {              System.out.println (ThreadName + "--no.--" + i);   }  //      }      }        }
4) Join () Method: Calls the method of a thread, and the current thread with the thread " Merge ", that is, wait for the thread to end before resuming the current thread's run. It can implement the function of thread merging, which is often used for the absolute scheduling of threads.
Package thread.schedule.v2;          public class Schedule {public static void main (string[] args) {Thread t1=new MyThread ("T1");            Thread t2=new MyThread ("T2");          T1.start ();          try {t1.join ();          } catch (Interruptedexception e) {e.printstacktrace ();          } System.out.println ("Main .....");          T2.start (); Note that if the T2 is placed before T1, then T2 will and T1 rob the resources, will not wait for the T1 to run, so there is no call to join () method after the thread to start}} class MyThread extends thread{private      Static Object Obj=new object ();            Private String Threadname=null;      Public MyThread (String threadname) {this.threadname = ThreadName;            } @Override public void Run () {System.out.println (".::::::::" + threadname);          for (int i = 1; i <=; i++) {System.out.println (threadname + "--no.--" + i);   }      }  }
5) Wait () method: The current thread enters the object's wait pool.

6) Notify ()/notifyall () method: Wake up one/all waiting threads in the wait pool of an object

Note: Wait and notify can only be used within the synchronization blocks of the instance they are called, and Sleep () is available everywhere.

The biggest difference between wait () and sleep () is that sleep () does not release object locks, and wait () is freed, so it is better to consider the wait () method in terms of efficiency.

3. Deadlock

Deadlock One:

Package thread.deadLock.lock1;          public class DeadLock {public static void main (string[] args) {s s=new s ();          Thread B=new Thread (new threadb (s));                    Thread A=new Thread (new Threada (s,b));          A.start ();      B.start ();  }} class S {public int a=0;      } class Threada implements runnable{private S s=null;            Private Thread B=null;          Public Threada (s S, Thread b) {this.s = s;      this.b = b;          } @Override public void Run () {System.out.println ("Now start threada------");              Synchronized (s) {//thread A first starts here to get the lock System.out.println (Thread.CurrentThread (). GetName () + "--a");              try {b.join ();//Here the B thread calls the Join () method, that is to wait for B to run out of other threads to run, but this time the lock is still in the hands, so there is a thread waiting for the b thread, B thread waiting for a thread, this is a deadlock phenomenon              } catch (Exception e) {e.printstacktrace ();          } System.out.println ("a=" +S.A);           }     }} class Threadb implements runnable{private S s=null;      Public threadb (s s) {this.s = s;          } @Override public void Run () {System.out.println ("New Start threadb------");              Synchronized (s) {s.a=100;          System.out.println (Thread.CurrentThread (). GetName () + "--b, a=" +S.A);   }      }        }
Deadlock Two:

Package Thread.deadLock.lock2;          public class DeadLock {public static void main (string[] args) {//If you want to resolve this multi-resource deadlock, you can package multiple resources into an integrated resource, The integrated resources into an object lock, which line Cheng to get the lock has all the resources//in the design phase should be taken into account----the multi-threaded each thread of the mutex resource drawing out-see which threads exist shared mutex resources,//and then analyze whether there may be a dead          Lock S1 s1=new S1 ();          S2 s2=new S2 ();          Thread A=new Thread (new Threada (S1,S2));          Thread B=new Thread (new threadb (S1,S2));          A.start ();      B.start ();  }} class S1 {public int a=1;  } class S2 {public int a=2;      } class Threada implements runnable{private S1 s1=null;            Private S2 S2=null;          Public Threada (S1 s1, S2 s2) {this.s1 = S1;      THIS.S2 = s2;          } @Override public void Run () {System.out.println ("Now start threada------");              Synchronized (S1) {//Here A thread gets the lock System.out.println (Thread.CurrentThread (). GetName () + "--a"); SYSTEM.OUT.PRINTLN ("Thread A output, s1.a="+S1.A);              SYSTEM.OUT.PRINTLN ("Thread A Gets the lock S1, but waits for the lock to S2"); Synchronized (S2) {//here if the front of the lock S1, the following B-thread also got the lock S2 then there will be a deadlock, the following B-thread will also deadlock, because A and B threads each hold each other part of the need to not put, so can not continue to go on,              But it is also possible that the B thread did not get the lock S2 when a thread took a breath to lock S1 and lock S2 ran out of deadlock System.out.println ("Thread A output, s2.a=" +s2.a);      }}}} class Threadb implements runnable{private S1 s1=null;            Private S2 S2=null;          Public threadb (S1 s1, S2 s2) {this.s1 = S1;      THIS.S2 = s2;          } @Override public void Run () {System.out.println ("Now start threadb------");              Synchronized (S2) {System.out.println (Thread.CurrentThread (). GetName () + "--b");              SYSTEM.OUT.PRINTLN ("Thread B output, s2.a=" +s2.a);              SYSTEM.OUT.PRINTLN ("Thread B gets the lock S2, but waits for the lock to S1");              Synchronized (S1) {System.out.println ("thread B output, s1.a=" +s1.a);   }          }      }  }

4. Related Concepts

1. The creation and startup threads are not the same: the thread does not actually start executing until a thread calls the start () method on the thread object of the new thread. The thread object already exists before its thread actually starts, and its thread exits after it is still present. Therefore, you can still control or get information about the thread that was created, even if the thread has not started or is finished.

2. End Thread:

1) thread arrives at the end of its run () method, it is recommended that this method is naturally ended.
2) The thread throws an uncaught exception or error.
3) Another thread calls a deprecated stop () method (not recommended).

3. Daemon thread (daemon thread): We mention that when all the threads of a Java program are finished, the program exits, but this is not entirely true because the program also hides the system threads. As the program starts, it catches the processing that meets its conditions during the run, which is the daemon thread.

5, attention to problems

1, synchronized must lock the object, the basic data type of the variable cannot be used as an object lock.

2, to ensure that multi-threaded use is the same mutex (object lock), in order to synchronize.

3, two kinds of deadlock:

1) Multiple threads share the same object lock, waiting for each other.
2) hold each other's required resources (that is, each thread needs to have multiple resources at the same time to continue execution, while multiple threads are in: Each holding part, waiting for another part. )

4, the resolution of the deadlock: to solve from the design aspects to avoid, that is, in the design of the consideration can not appear deadlock.
Luo lists all critical resources, plots the distribution map, observes the deadlock situation, and changes the way in which the thread's (critical) resources are acquired.
Design principle: Try to make the program less critical resources.

5, Wait/notify and sleep methods: Wait and notify can only be used within the synchronization block of the instance they are called, and Sleep () is available everywhere. The biggest difference between wait () and sleep () is that sleep () does not release object locks, and wait () is freed, so it is better to consider the wait () method in terms of efficiency.

6. The basic principle of synchronous design: the smaller the code in the synchronization block (synchronized) the better!
Do not write blocking code in the synchronization block (for example, Inputstream.read ())!
Do not invoke methods on other objects while holding the lock. (If you do, you can eliminate the most common source of deadlocks.) )

7, synchronization Overview:

The principle of synchronization: encapsulate the code that needs to be synchronized and add a lock to the code.
The benefits of synchronization: Addressing the security issues of multithreading.
The disadvantage of synchronization: it degrades performance.
Prerequisites for synchronization: You must ensure that there are multiple threads and that they are using the same lock in the synchronization.



Java------Multithreading (enhanced)

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.