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