Thread Synchronization Method: (1) Synchronous Code block, format:
Synchronized (synchronization object ){
// Synchronize code
}
(2) synchronization method. format:
Add synchronized BEFORE THE METHOD
Problem:
Multiple people buy tickets at the same time.
1. Resources are not synchronized.
package thread;public class Tickets implements Runnable {private int count = 5;@Overridepublic void run() {for (int i = 0; i < 10; ++i) {if (count > 0) {try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(count--);}}}public static void main(String[] args) {Tickets tickets=new Tickets(); Thread t1=new Thread(tickets); Thread t2=new Thread(tickets); Thread t3=new Thread(tickets); t1.start(); t2.start(); t3.start(); }}
Running result:
534221
Obviously, the result is wrong.
2. synchronous code block
Synchronization in the run method, that is, synchronization of shared resources (number of votes, count)
package thread;public class Tickets implements Runnable {private int count = 5;@Overridepublic void run() {for (int i = 0; i < 10; ++i) {synchronized (this) {if (count > 0) {try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(count--);}}}}public static void main(String[] args) {Tickets tickets = new Tickets();Thread t1 = new Thread(tickets);Thread t2 = new Thread(tickets);Thread t3 = new Thread(tickets);t1.start();t2.start();t3.start();}}
3. Synchronization Method
package thread;public class Tickets implements Runnable {private int count = 5;@Overridepublic void run() {for (int i = 0; i < 10; ++i) {sale();}}public synchronized void sale() {if (count > 0) {try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(count--);}}public static void main(String[] args) {Tickets tickets = new Tickets();Thread t1 = new Thread(tickets);Thread t2 = new Thread(tickets);Thread t3 = new Thread(tickets);t1.start();t2.start();t3.start();}}
Reference: http://www.cnblogs.com/rollenholt/archive/2011/08/28/2156357.html. We hereby declare that.