Java note 6. Thread Synchronization and deadlock

Source: Internet
Author: User

Java note 6. Thread Synchronization and deadlock
Thread Synchronization and thread deadlock in the previous article, there is a simulated train ticket sales system. In the program code that sells tickets, it is very likely to encounter an accident, that is, the same ticket number is printed twice or multiple times, and a 0 or even negative number may be printed. Specifically, suppose that when the value of tickets is 1, thread 1 just executes the if (tickets> 0) line of code and is preparing to execute the following code, the operating system switches the CPU to thread 2 for execution. At this time, the value of tickets is still 1. After thread 2 executes the above two lines of code, the value of tickets is changed to 0, the CPU is switched back to thread 1 for execution, and thread 1 will not execute the if (tickets> 0) line of code, because it has been compared before and the comparison result is true, thread 1 continues to run the subsequent code, and the value of tickets is 0, which is not allowed.
I. Thread Synchronization 1. Thread SynchronizationTo solve the problem of non-synchronization between multiple threads and the same resource, we can do this, that is, when a thread runs to if (tickets> 0, the code block that the CPU does not execute in other threads and may affect the execution result of the next code sentence in the current thread. It must wait until the next execution is complete before executing the relevant code block in other threads. This code is like a bridge. At any time, only one person can walk on the bridge. In the program, there cannot be multiple threads simultaneously executed between the two sentences. This is thread synchronization.2. synchronized statementFormat: synchronized (object) {code segment} // pbject can be any code segment in the synchronized statement of an object, forming a synchronous code block. That is to say, at the same time, only one thread can enter the synchronization code block to run. Only when the thread leaves the synchronization code block can other threads enter the synchronization code block to run. An object of any type has a flag. The flag has two states: 0 and 1. The initial state is 1. When synchronized (object) is executed) after the statement, the flag of the object changes to the 0 state, knowing that the code block in the complete synchronized statement is returned to the 1 state. When a thread executes the synchronized (object) statement, it first checks the flag of the object (that is, the lock flag of the synchronization object). If the status is 0, it indicates that another thread's execution status is in the synchronization code block. This thread will be temporarily blocked, giving way to the CPU resources and knowing that the other thread has finished executing the synchronization code block, the block that restores the flag of the object to 1 is canceled. An object used for synchronized statements is called a monitor. When a thread obtains the execution right of the code block in the synchronized (object) statement, it means that it has locked the monitor for a period of time, only one thread can lock the monitor. The thread also releases the flag when the synchronization block code is completed or when a break statement or an exception is thrown.Synchronized statement:

Public class DemoThread {public static void main (String [] args) {ThreadTest runnable = new ThreadTest (); // declare a Runnable subclass object new Thread (runnable ). start (); // create four threads, which use the same resource new Thread (runnable ). start (); new Thread (runnable ). start (); new Thread (runnable ). start () ;}// implement a Runnable subclass public class ThreadTest implements Runnable {int tickets = 100; String str = new String (); // define 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: if we define the lock flag of the synchronized synchronization object in the run () method, multithreading cannot implement synchronization. This is because when a thread starts, it will call the run method. For each call, the program generates a different str local object, the synchronization monitors used by these four threads are completely four different objects, so they cannot be synchronized with each other. 3. Different code blocks are synchronized with each otherThe synchronization code block we mentioned above refers to not only synchronizing the same code block among multiple threads. Of course, several different code blocks can also synchronize with each other, as long as the objects in the synchronized (object) statements are completely the same object. 4. synchronous FunctionsIn addition to synchronizing code blocks, you can also synchronize functions, that is, you only need to add the synchronized keyword before the function definition to be synchronized. (1) DemoThread. java
Public class DemoThread {public static void main (String [] args) {ThreadTest runnable = new ThreadTest (); // declare a Runnable subclass object new Thread (runnable ). start (); // create four threads, which use the same resource new Thread (runnable ). start (); new Thread (runnable ). start (); new Thread (runnable ). start ();}}
(2) ThreadTest. java // implement a 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(1000);    }    catch(Exception e)    {     e.printStackTrace();    }    System.out.println(Thread.currentThread().getName()+ is saling tickets+tickets--);   } }}

Analysis 1: In the same category, several methods defined using the synchronized keyword can be synchronized between multiple threads. When a thread enters the synchronized modification method (obtain the monitor ), other threads will not be able to access all the methods using synchronized modification for the same object until the first thread finishes executing the synchronized modification method it enters (leaving the monitor ). Analysis 2: We observe the program results and find that the program is slower than when no synchronization processing is used. This is because the system constantly monitors the synchronization monitor, requires more time overhead. Therefore, synchronization is at the cost of program performance. If we can determine that the program has no security issues, we do not need to use synchronization control. Analysis 3: When synchronizing code blocks and functions, because the monitor used by the synchronous function is this object (an object that can always be accessed by non-static methods in the class is this object itself ), therefore, this object should be used as the synchronization monitor in the synchronization code block.
Ii. Thread deadlockDeadlock is a rare and difficult to debug error. A deadlock occurs when two threads have a circular dependency on two synchronization objects. For example, if a thread enters the monitor of object X and another object enters the monitor of object Y, the thread that enters the X object monitor will be blocked if it tries to enter the monitor of object Y, then the thread that enters the Y object monitor will be blocked if it tries to enter the monitor of the X object, so that both threads are suspended. (1) A. java
Public class A {synchronized void foo (B B) {String name = Thread. currentThread (). getName (); // get the name of the current thread System. out. println (name + enter. foo); try {Thread. sleep (100);} catch (Exception e) {e. printStackTrace ();} System. out. println (name + is trying to call B. last); B. last ();} synchronized void last () {System. out. println (inside. last );}}

(2) B. java
Public class B {synchronized void bar (A a) {String name = Thread. currentThread (). getName (); // get the name of the current thread System. out. println (name + enter B. bar); try {Thread. sleep (100);} catch (Exception e) {e. printStackTrace ();} System. out. println (name + is trying to call B. last);. last ();} synchronized void last () {System. out. println (inside B. last );}}
(3) BlockRunnable. java
Public class BlockRunnable implements Runnable {A = new a (); // create A class A object B = new B (); // create A class B object BlockRunnable () // constructor {Thread. currentThread (). setName (MainThread); // set the main Thread name new Thread (this ). start (); // create and start a sub-thread. foo (B); // calls the foo method of Class a in the main thread. The foo method tries to call the bar method of Class B System. out. println (back in the Main thread);} public void run () {Thread. currentThread (). setName (ChildThread); B. bar (a); System. out. println (back in the ChildThread);} // master public static void main (String [] args) {new BlockRunnable ();}}



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.