In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/03 Report--
Synchronized: synchronization (lock), which can modify code blocks and methods. Once the modified code blocks and methods are accessed by one thread, they are locked directly, and other threads will not be able to access the synchronization lock object of non-static methods is this.
The lock synchronization object of the static method is the bytecode object of the current class
A case of simulated ticket sales at railway station
Synchronize code blocks:
Public class Ticket implements Runnable {
Int tickets = 100 if / Total votes Object obj = new Object (); / / Lock object @ Overridepublic void run () {/ / ticket selling while (true) {synchronized (obj) {if (tickets > 0) {try {Thread.sleep (10);} catch (InterruptedException e) {e.printStackTrace () } System.out.println (Thread.currentThread (). GetName () + "sold" + (tickets--) + "ticket");}
}
Synchronization method
Public class Ticket implements Runnable {
Int tickets = 100 if / Total votes Object obj = new Object (); / / Lock object @ Overridepublic void run () {/ / ticket selling while (true) {method ();}} public synchronized void method () {if (tickets > 0) {try {Thread.sleep (10);} catch (InterruptedException e) {e.printStackTrace () } System.out.println (Thread.currentThread (). GetName () + "sold" + (tickets--) + "ticket");}}
}
Test class
Public class TicketTest {
Public static void main (String args []) {
Ticket t = new Ticket (); Thread T1 = new Thread (t); Thread T2 = new Thread (t); Thread T3 = new Thread (t); t1.setName (window 1); t2.setName (window 2); t3.setName (window 3); t1.start (); t2.start (); t3.start ();}
}
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.