Synchronous code block to achieve multi-threaded secure ticketing case

Class tickets implements the runnable interface:

/** use the synchronization method to solve the thread safety problem * benefits: the amount of code is concise * extract the thread shared data and synchronization into a method * add the synchronization keyword to the method declaration * * question: * delete obj, is there a lock in the synchronization method? There must be. The object lock in the synchronization method refers to this * if the method is static, does the synchronization have a lock? Is that this? Definitely not this, the lock is the class itself Class attribute * static method. Synchronization lock is the class name of this class Class attribute * / public class tickets implements runnable {/ / defines the ticket source that can be sold private static int ticket = 100; / / private object obj = new object(); public void run() {while (true) {payticket();}} Public static synchronized void payticket() {/ / judge the number of votes. If it is greater than 0, it can be sold. If (ticket > 0) {try {thread.sleep (10);} catch(Exception ex){} System. out. println(Thread.currentThread(). Getname() + "sale" + ticket --);}}

}

Test demo class:

/** multiple threads access the same data resource concurrently * 3 threads for one ticket resource, Sell * / public class threaddemo {public static void main (string [] args) {/ / create a runnable interface to implement class objects tickets t = new tickets(); / / create three thread class objects and pass the runnable interface implementation class thread t0 = new thread (T); thread T1 = new thread (t); thread T2 = new thread (T); t0. Start(); T1. Start(); T2. Start();}}

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>