Java multi-thread thread synchronization
Thread synchronization
definition: synchronization means that only one thread can run within the same time period.
Category: synchronization Methods , synchronization blocks.
role: Security to resolve sharing issues.
Sync Block:
Grammar:
synchronized (synchronizing objects) {
Code that needs to be synchronized;
}
Example:
public class Threaddemo implements runnable{private int ticket = 5;public void Run () {for (int i=1;i<=5;i++) {Synchronize D (This) {if (ticket>0) { thread.sleep (+); SYSTEM.OUT.PRINTLN ("Sell ticket: ticket=" +ticket--);}}}
Synchronization method:
Grammar:
Synchronized method return value method name (parameter list) {
}
Example:
public class Threaddemo implements runnable{private int ticket = 5;public void Run () {for (int i=1;i<=5;i++) {This.saleti Cket ();}} Public synchronized void Saleticket () {if (ticket>0) {thread.sleep (1000); SYSTEM.OUT.PRINTLN ("Sell ticket: ticket=" +ticket--);}
A complete example of a synchronization method:
public class Timer { private static int num = 0; Public synchronized void Add (String name) {//During the execution of this method, the current object is locked num + +; try { thread.sleep (1); } catch (Interruptedexception e) { //TODO auto-generated catch block E.printstacktrace (); } SYSTEM.OUT.PRINTLN (name + "You are the first" +num + "thread using the Timer"); } } public class Testsync implements runnable{ Timer timer = new timer (); public static void Main (string[] args) { Testsync testsync = new Testsync (); thread T1 = new Thread (testsync); Thread t2 = new Thread (testsync); T1.setname ("T1"); T2.setname ("T2"); T1.start (); T2.start (); } public void Run () { timer.add (Thread.CurrentThread (). GetName ()); } }
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Java multi-thread----thread synchronization