Java: Synchronization and deadlock

Source: Internet
Author: User

Synchronization is required when multiple threads share a resource (otherwise an error occurs: such as negative numbers, repetitions), but excessive synchronization can cause deadlocks.

Synchronized (This)

{

}

Non-synchronous condition:

public class Syncthread implements Runnable {private int titick = 5; @Overridepublic void Run () {//TODO auto-generated method stub for (int i = 0; I <50; i++) {if (This.titick > 0) {//If a delay condition is encountered, the try {thread.sleep ()}, the catch (Interruptedexception e) {//TODO auto-generated catch Block E.printstacktrace ();} System.out.println ("Sell to:" + this.titick--+ "Ticket");}}} public class Demo {public static void main (string[] args) {//TODO auto-generated method stub Syncthread st = new Syncthread (); New Thread (St , "Scalper a"). Start (); New Thread (St, "Scalper B"). Start (); New Thread (St, "Scalper C"). Start ();}}

Results:

  

Synchronization situation:

public class SyncThread2 implements Runnable {private int titict = 5; @Overridepublic void Run () {//TODO automatically generated method stub for (int i = 0; I < 50; i++) {synchronized (this) {if (this.titict > 0) {try {thread.sleep];} catch (Interruptedexception e) {//TODO auto-generated CA TCH block E.printstacktrace ();} System.out.println ("Sell:" + this.titict--);}}}} public class Demo2 {public static void main (string[] args) {//TODO auto-generated method stub SyncThread2 sy2 = new SyncThread2 (); new Threa D (Sy2, "Scalper 1"). Start (); New Thread (Sy2, "Scalper 2"). Start (); New Thread (Sy2, "Scalper 3"). Start ();}}

Results:

Java: Synchronization and 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.