Synchronized of the thread and synchronized

Source: Internet
Author: User

Synchronized of the thread and synchronized
Data can be shared among multiple threads of a Java program.When a thread accesses shared data asynchronously, it is sometimes insecure or non-logical. For example, when a train ticket is sold, one thread is reading data at the same time, and the other thread is processing data. When the data processing thread does not wait until the Data Reading thread completes, it will process the data, the error processing result is inevitable.
Train ticket sales Demo:

Class MyThread implements Runnable {private int ticket = 5; // assume a total of five tickets are public void run () {for (int I = 0; I <100; I ++) {if (ticket> 0) {// There are tickets try {Thread. sleep (300); // Add latency} catch (InterruptedException e) {e. printStackTrace ();} System. out. println ("selling tickets: ticket =" + ticket --) ;}}}; public class SyncDemo01 {public static void main (String args []) {MyThread mt = new MyThread (); // defines the Thread object Thread t1 = new Thread (mt); // defines the Thread object Thread t2 = new Thread (mt ); // define the Thread object Thread t3 = new Thread (mt); // define the Thread object t1.start (); t2.start (); t3.start ();}};
The following results may be displayed during running:... sell tickets: ticket = 1 sell tickets: ticket = 0 sell tickets: ticket =-1
The Java programming language provides a simple mechanism to prevent such coverage. Each object has an associated lock at runtime. This lock can be obtained by adding the key word synchronized to the method.Two synchronous methods are available: Synchronous block and synchronous method.
Synchronization block: Lock conflicting statement Blocks
Class MyThread implements Runnable {private int ticket = 5; // assume a total of five tickets are public void run () {for (int I = 0; I <100; I ++) {synchronized (this) {// synchronize the current object if (ticket> 0) {// There is a ticket try {Thread. sleep (300); // Add latency} catch (InterruptedException e) {e. printStackTrace ();} System. out. println ("selling tickets: ticket =" + ticket --) ;}}}; public class SyncDemo02 {public static void main (String args []) {MyThread mt = new MyThread (); // defines the Thread object Thread t1 = new Thread (mt); // defines the Thread object Thread t2 = new Thread (mt ); // define the Thread object Thread t3 = new Thread (mt); // define the Thread object t1.start (); t2.start (); t3.start ();}};


Synchronization Method: Lock method blocks that are prone to conflicts
Class MyThread implements Runnable {private int ticket = 5; // assume a total of five tickets are public void run () {for (int I = 0; I <100; I ++) {this. sale (); // call the synchronization method} public synchronized void sale () {// declare the synchronization method if (ticket> 0) {// There are also tickets try {Thread. sleep (300); // Add latency} catch (InterruptedException e) {e. printStackTrace ();} System. out. println ("selling tickets: ticket =" + ticket --) ;}}; public class SyncDemo03 {public static void main (String args []) {MyThread mt = new MyThread (); // define the Thread object Thread t1 = new Thread (mt); // define the Thread object Thread t2 = new Thread (mt ); // define the Thread object Thread t3 = new Thread (mt); // define the Thread object t1.start (); t2.start (); t3.start ();}};







Why is only one thread running after synchronized synchronization in java?

. Modified it., so it should be okay.
Class TextThread implements Runnable {
Private int tickets = 20;
Public void run ()
{
For (int I = 0; I <= 20; I ++ ){
Go ();
}
}
Public synchronized void go (){

If (tickets> 0 ){
Try {
Thread. sleep (100 );
}
Catch (Exception x ){}
System. out. println (Thread. currentThread (). getName () + "sold tickets" + tickets --);
}
}
}

Teach JAVA the thread synchronization mechanism synchronized

1. First, you must know what synchronized means: only when two threads synchronize synchronized to the same object can the synchronization effect be generated. Otherwise, if thread A synchronizes to object, thread B is useless to synchronize object B. Thread A and thread B must synchronize the same object c.
If synchronized modifies a method, it means to synchronize the object where the method is located. Therefore, if you use the synchronized modification method, but you have new two different objects, of course, synchronization cannot be implemented. If synchronized is used to modify "a", the string constants of the same content are the same object in java, So synchronization can be implemented.

2. The start method of the Thread class still calls the run method in the MyThread object that you pass to it. Although there are two Thread objects, the run method of my object is executed, of course, it can be synchronized.

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.