Java note Six. Thread synchronization, thread deadlock

Source: Internet
Author: User
Tags ticket

thread synchronization, thread deadlockIn the previous article, there is a simulation of the sale of train ticket system, in the ticket sales program code, it is very likely to encounter an accident, that is, the same ticket number is printed two times, may also appear to print out 0 or even a negative number of the ticket. In the following scenario: Assuming that the value of tickets is 1, thread 1 has just finished executing the IF (tickets>0) line and is preparing to execute the code below, at which point the operating system switches the CPU to thread 2, where the value of tickets is still 1. Thread 2 Executes the above two lines of code, after the value of tickets becomes 0, the CPU is cut back to thread 1 execution, and thread 1 no longer executes the IF (tickets>0) line of code, because it was previously compared, and the result of the comparison is true, thread 1 continues to execute the following code, The result is that the value of tickets is 0, which we do not allow.
one, thread synchronization 1. Thread Synchronizationin order to solve the problem of synchronization of the same resource in the multithreading operation above, we can do this, that is, when a thread runs to if (tickets>0), the CPU does not execute the code block in other threads, which may affect the execution result of the next sentence code in the current thread. You must wait until the next sentence executes before you can execute the relevant code block in the other thread . This code is like a single-plank bridge, at any time, there can only be one person walking on the bridges, the program can not have multiple threads at the same time between the two code execution, which is thread synchronization. 2.synchronized Statementsformat:synchronized (object) {code snippet}//pbject can be an arbitrary objectsynchronized the code snippet within the statement, the synchronization code block is formed. In other words, only one thread can enter at the same timesynchronizing within a code blockruns only if the thread leaves the synchronization code block and the other thread can run inside the synchronization code block. object is of any type, and the object has a flag bit with 0, 12 states with a starting state of 1, and when the synchronized (object) statement is executed, the object's flag bit becomes 0 state. Knowing that a block of code in the complete synchronized statement was executed, it returned to the 1 state. When a thread executes to a synchronized (object) statement, it first checks The flag bit of the object ( that is, the lock flag of the synchronization object ) , if the status of 0 indicates that there is already an execution state of another thread in the relevant synchronization code block, this thread will temporarily block, yielding the CPU resources, knowing that another thread is executing the relevant synchronization code block and restoring the object object's flag bit to the 1 state that the blocking is canceled. An object used in a synchronized statement is called a monitor, and when a thread obtains the execution of a block of code in a synchronized (object ) statement, That means it locks the monitor, and for a period of time only one thread can lock the monitor. The thread also releases the lock flag when the synchronization block code finishes executing or encounters a break statement or throws an exception. Synchronized Statement Synchronization code implementation:
public class DemoThread {public static void main (string[] args) {threadtest runnable = new ThreadTest ();//Declare a runnable subclass object NE W Thread (runnable). Start ();   Create four threads that use the same resource new thread (runnable). Start ();   New Thread (runnable). Start ();  New Thread (runnable). Start (); }}//implements a Runnable subclass public class ThreadTest implements Runnable {int tickets=100;    String str = new string ();       Defines a lock flag public void run () {while (true) {synchronized (str) {if (tickets>0) {try {      Thread.Sleep (1000);      } catch (Exception e) {e.printstacktrace ();     } System.out.println (Thread.CurrentThread (). GetName () + "is saling tickets" +tickets--); }    }   } }}
Analysis : multithreading cannot be synchronized if we define the lock flag of a synchronized synchronization object in the run () method. That's because when a thread starts it will call the Run method, and for each call, the program produces a different STR local object, which is four threads that use a synchronization monitor that is completely four different objects, so they cannot be synchronized with each other. 3. Different code blocks are synchronized with each other The synchronization code block we mentioned above means that not only the same code block is synchronized between multiple threads. Of course, several different blocks of code can also be synchronized with each other , as long as the object in each synchronized (object) statement is exactly the same object. 4. Synchronization functions In addition to synchronizing code blocks, you can synchronize functions by adding the Synchronized keyword to a function definition that requires synchronization. (1) Demothread.java
public class DemoThread {public  static void Main (string[] args)  {   threadtest runnable = new ThreadTest ();//Sound Ming a runnable Subclass object    new Thread (runnable). Start ();//create four threads that use the same resource    new thread (runnable). Start ();   New Thread (runnable). Start ();   New Thread (runnable). Start ();  }}
(2) Threadtest.java//Implement an runnable subclass
public class ThreadTest implements runnable{int tickets=100, public void Run () {   while (true)   {    sale ();   } public synchronized void  sale () {   if (tickets>0)   {    try    {     thread.sleep ();    }    catch (Exception e)    {     e.printstacktrace ();    }    System.out.println (Thread.CurrentThread (). GetName () + "is saling tickets" +tickets--);   }}

< Span style= "Background-color:inherit" > analysis 1 in the same class, several methods defined with the Synchronized keyword can be synchronized between multiple threads, and when a thread enters a synchronized-decorated method (to get a monitor), Other threads cannot enter all methods that use the synchronized adornment of the same object until the first thread finishes executing the synchronized adornment it enters is unknown (leaving the monitor). Analysis 2: We found through the observation program results that the program runs faster than the original synchronization is not used, it is because the system is constantly on the synchronization monitor, the need for more time overhead. So synchronization is at the expense of the performance of the program, and if we can determine that there is no security problem with the program, there is no need to use synchronization control. Analysis 3: when synchronizing between code blocks and functions, the This object should be used as the synchronization monitor in a synchronous code block because the monitor used by the synchronization function is the This object (an object that is always accessible to non-static methods in the Class).
two, thread deadlock deadlocks are a rare and difficult error to debug, and deadlock occurs when two threads have cyclic dependencies on two synchronization objects . For example, when a thread enters the monitor for object x, and another object enters the monitor for object y, the thread that enters the X object monitor will be blocked if the monitor that is still trying to enter the Y object, and then the thread that enters the Y object monitor, will be blocked if it tries to enter the X object. So two threads are in a suspended state. (1) A.java
public class A {synchronized void foo (b b) {  String name = Thread.CurrentThread (). GetName ();//Gets the name of the current thread  SYSTEM.O Ut.println (name+ "Enter A.foo");  Try  {   thread.sleep (+);  }  catch (Exception e)  {   e.printstacktrace ();  }  System.out.println (name+ "is trying to call B.last");  B.last (); } synchronized  void last () {  System.out.println ("Inside A.last");}}

(2) B.java
public class B {synchronized void bar (a a) {  String name = Thread.CurrentThread (). GetName ();//Gets the name of the current thread  SYSTEM.O Ut.println (name+ "Enter B.bar");  Try  {   thread.sleep (+);  }  catch (Exception e)  {   e.printstacktrace ();  }  System.out.println (name+ "is trying to call B.last");  A.last (); } synchronized  void last () {  System.out.println ("Inside B.last");}}
(3) Blockrunnable.java
public class Blockrunnable implements runnable{a a=new a ();//Create a Class A object B b=new b ();//Create a Class B object Blockrunnable ()  //construction method {  thread.currentthread (). SetName ("Mainthread");//Set the main thread name  new Thread (this). Start ();//Create and start a child thread  A.foo (b); The main thread calls the Class A Foo method, and the Foo method attempts to invoke the bar method of Class B  System.out.println ("Back in the Main thread"), and the public void Run () {  Thread.CurrentThread (). SetName ("Childthread");  B.bar (a);  System.out.println ("Back in the Childthread"); }//main public static void main (string[] args) {  new blockrunnable ();}}



Java note Six. Thread synchronization, thread deadlock

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.