1. บทนำ
ในบทความนี้เราจะดูหนึ่งในกลไกพื้นฐานที่สุดใน Java นั่นคือการซิงโครไนซ์เธรด
ก่อนอื่นเราจะพูดถึงคำศัพท์และระเบียบวิธีที่เกี่ยวข้องกับการทำงานพร้อมกันที่จำเป็น
และเราจะพัฒนาแอปพลิเคชันง่ายๆ - ที่ซึ่งเราจะจัดการกับปัญหาการเกิดพร้อมกันโดยมีเป้าหมายเพื่อทำความเข้าใจกับการรอ ()และแจ้ง () ให้ดีขึ้น
2. การซิงโครไนซ์เธรดใน Java
ในสภาพแวดล้อมแบบมัลติเธรดหลายเธรดอาจพยายามแก้ไขทรัพยากรเดียวกัน หากเธรดไม่ได้รับการจัดการอย่างเหมาะสมสิ่งนี้จะนำไปสู่ปัญหาความสอดคล้อง
2.1. Guarded Blocks ใน Java
เครื่องมือหนึ่งที่เราสามารถใช้เพื่อประสานการดำเนินการของหลายเธรดใน Java - คือบล็อกที่มีการป้องกัน บล็อกดังกล่าวจะตรวจสอบเงื่อนไขเฉพาะก่อนที่จะดำเนินการต่อ
ด้วยเหตุนี้เราจึงใช้ประโยชน์จาก:
- Object.wait () - เพื่อระงับเธรด
- Object.notify () -เพื่อปลุกเธรด
สิ่งนี้สามารถเข้าใจได้ดีขึ้นจากแผนภาพต่อไปนี้ซึ่งแสดงถึงวงจรชีวิตของเธรด :

โปรดทราบว่ามีหลายวิธีในการควบคุมวงจรชีวิตนี้ อย่างไรก็ตามในบทความนี้เราจะเน้นเฉพาะwait ()และalert ()
3. รอ ()วิธี
พูดง่ายๆก็คือเมื่อเราเรียกwait () -สิ่งนี้บังคับให้เธรดปัจจุบันรอจนกว่าเธรดอื่นจะเรียกใช้การแจ้งเตือน ()หรือแจ้งเตือนทั้งหมด()บนอ็อบเจ็กต์เดียวกัน
สำหรับสิ่งนี้เธรดปัจจุบันต้องเป็นเจ้าของจอภาพของวัตถุ ตาม Javadocs สิ่งนี้สามารถเกิดขึ้นได้เมื่อ:
- เราได้เรียกใช้วิธีการซิงโครไนซ์อินสแตนซ์สำหรับวัตถุที่กำหนด
- เราได้ดำเนินการร่างของบล็อกที่ซิงโครไนซ์บนวัตถุที่กำหนด
- โดยการเรียกใช้เมธอดแบบคงที่ซิงโครไนซ์สำหรับอ็อบเจ็กต์ประเภทClass
โปรดทราบว่าเธรดที่ใช้งานอยู่เพียงชุดเดียวเท่านั้นที่สามารถเป็นเจ้าของจอภาพของวัตถุได้ในแต่ละครั้ง
วิธีwait ()นี้มาพร้อมกับลายเซ็นที่มากเกินไปสามแบบ ลองดูสิ่งเหล่านี้
3.1. รอ()
รอ ()วิธีการที่ทำให้เกิดเธรดปัจจุบันที่จะรอไปเรื่อย ๆ จนกว่าจะมีหัวข้ออื่นจะเรียกทั้งแจ้ง ()สำหรับวัตถุนี้หรือnotifyAll ()
3.2. รอ (หมดเวลานาน)
เมื่อใช้วิธีนี้เราสามารถระบุการหมดเวลาหลังจากนั้นเธรดจะถูกปลุกโดยอัตโนมัติ ด้ายสามารถตื่นขึ้นมาก่อนที่จะถึงการหมดเวลาใช้แจ้ง ()หรือnotifyAll ()
โปรดทราบว่าการโทรรอ (0)เหมือนกับการโทรรอ ()
3.3. รอ (long timeout, int nanos)
นี่เป็นอีกหนึ่งลายเซ็นที่ให้ฟังก์ชันการทำงานเดียวกันโดยมีข้อแตกต่างเพียงอย่างเดียวคือเราสามารถให้ความแม่นยำที่สูงขึ้นได้
ระยะหมดเวลาทั้งหมด (ในหน่วยนาโนวินาที) คำนวณเป็น1_000_000 * หมดเวลา + นาโนเมตร
4. แจ้ง ()และแจ้งเตือนทั้งหมด()
วิธีการแจ้งเตือน ()ใช้สำหรับการปลุกเธรดที่กำลังรอการเข้าถึงมอนิเตอร์ของอ็อบเจ็กต์นี้
มีสองวิธีในการแจ้งเตือนเธรดที่รออยู่
4.1. แจ้ง()
สำหรับเธรดทั้งหมดที่รออยู่บนมอนิเตอร์ของอ็อบเจ็กต์นี้ (โดยใช้วิธีการwait ()วิธีใดวิธีหนึ่ง) วิธีการแจ้งเตือน ()จะแจ้งให้คนใดคนหนึ่งตื่นขึ้นมาโดยพลการ การเลือกเธรดที่จะปลุกนั้นไม่ได้ถูกกำหนดขึ้นและขึ้นอยู่กับการนำไปใช้งาน
ตั้งแต่แจ้ง ()ตื่นขึ้นมาด้ายสุ่มเดียวก็สามารถนำมาใช้ในการดำเนินการล็อคพิเศษร่วมกันที่กระทู้จะทำหน้าที่คล้ายกัน แต่ในกรณีส่วนใหญ่ก็จะทำงานได้มากขึ้นที่จะใช้notifyAll ()
4.2. แจ้งทั้งหมด ()
วิธีนี้จะปลุกเธรดทั้งหมดที่รออยู่บนมอนิเตอร์ของวัตถุนี้
เธรดที่ปลุกแล้วจะเสร็จสมบูรณ์ในลักษณะปกติเช่นเดียวกับเธรดอื่น ๆ
แต่ก่อนที่เราจะอนุญาตให้ดำเนินการต่อให้กำหนดการตรวจสอบอย่างรวดเร็วสำหรับเงื่อนไขที่จำเป็นในการดำเนินการกับเธรด - เนื่องจากอาจมีบางสถานการณ์ที่เธรดถูกปลุกโดยไม่ได้รับการแจ้งเตือน (สถานการณ์นี้จะกล่าวถึงในตัวอย่างในภายหลัง) .
5. ปัญหาการซิงโครไนซ์ผู้ส่งและผู้รับ
ตอนนี้เราเข้าใจพื้นฐานแล้วเรามาดูแอปพลิเคชันSender - Receiverแบบง่ายๆซึ่งจะใช้ประโยชน์จากวิธีwait ()และแจ้ง ()เพื่อตั้งค่าการซิงโครไนซ์ระหว่างกัน:
- ผู้ส่งควรจะส่งแพ็คเก็ตข้อมูลไปยังผู้รับ
- ผู้รับไม่สามารถดำเนินการส่งข้อมูลจนส่งเสร็จสิ้นส่ง
- ในทำนองเดียวกันผู้ส่งจะต้องไม่พยายามส่งแพ็กเก็ตอื่นเว้นแต่ว่าผู้รับจะประมวลผลแพ็กเก็ตก่อนหน้านี้แล้ว
Let's first create Data class that consists of the data packet that will be sent from Sender to Receiver. We'll use wait() and notifyAll() to set up synchronization between them:
public class Data { private String packet; // True if receiver should wait // False if sender should wait private boolean transfer = true; public synchronized void send(String packet) { while (!transfer) { try { wait(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); Log.error("Thread interrupted", e); } } transfer = false; this.packet = packet; notifyAll(); } public synchronized String receive() { while (transfer) { try { wait(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); Log.error("Thread interrupted", e); } } transfer = true; notifyAll(); return packet; } }
Let's break down what's going on here:
- The packet variable denotes the data that is being transferred over the network
- We have a boolean variable transfer – which the Sender and Receiver will use for synchronization:
- If this variable is true, then the Receiver should wait for Sender to send the message
- If it's false, then Sender should wait for Receiver to receive the message
- The Sender uses send() method to send data to the Receiver:
- If transfer is false, we'll wait by calling wait() on this thread
- But when it is true, we toggle the status, set our message and call notifyAll() to wake up other threads to specify that a significant event has occurred and they can check if they can continue execution
- Similarly, the Receiver will use receive() method:
- If the transfer was set to false by Sender, then only it will proceed, otherwise we'll call wait() on this thread
- When the condition is met, we toggle the status, notify all waiting threads to wake up and return the data packet that was Receiver
5.1. Why Enclose wait() in a while Loop?
Since notify() and notifyAll() randomly wakes up threads that are waiting on this object's monitor, it's not always important that the condition is met. Sometimes it can happen that the thread is woken up, but the condition isn't actually satisfied yet.
We can also define a check to save us from spurious wakeups – where a thread can wake up from waiting without ever having received a notification.
5.2. Why Do We Need to Synchronize send() and receive() Methods?
We placed these methods inside synchronized methods to provide intrinsic locks. If a thread calling wait() method does not own the inherent lock, an error will be thrown.
We'll now create Sender and Receiver and implement the Runnable interface on both so that their instances can be executed by a thread.
Let's first see how Sender will work:
public class Sender implements Runnable { private Data data; // standard constructors public void run() { String packets[] = { "First packet", "Second packet", "Third packet", "Fourth packet", "End" }; for (String packet : packets) { data.send(packet); // Thread.sleep() to mimic heavy server-side processing try { Thread.sleep(ThreadLocalRandom.current().nextInt(1000, 5000)); } catch (InterruptedException e) { Thread.currentThread().interrupt(); Log.error("Thread interrupted", e); } } } }
For this Sender:
- We're creating some random data packets that will be sent across the network in packets[] array
- For each packet, we're merely calling send()
- Then we're calling Thread.sleep() with random interval to mimic heavy server-side processing
Finally, let's implement our Receiver:
public class Receiver implements Runnable { private Data load; // standard constructors public void run() { for(String receivedMessage = load.receive(); !"End".equals(receivedMessage); receivedMessage = load.receive()) { System.out.println(receivedMessage); // ... try { Thread.sleep(ThreadLocalRandom.current().nextInt(1000, 5000)); } catch (InterruptedException e) { Thread.currentThread().interrupt(); Log.error("Thread interrupted", e); } } } }
Here, we're simply calling load.receive() in the loop until we get the last “End” data packet.
Let's now see this application in action:
public static void main(String[] args) { Data data = new Data(); Thread sender = new Thread(new Sender(data)); Thread receiver = new Thread(new Receiver(data)); sender.start(); receiver.start(); }
We'll receive the following output:
First packet Second packet Third packet Fourth packet
And here we are – we've received all data packets in the right, sequential order and successfully established the correct communication between our sender and receiver.
6. Conclusion
In this article, we discussed some core synchronization concepts in Java; more specifically, we focused on how we can use wait() and notify() to solve interesting synchronization problems. And finally, we went through a code sample where we applied these concepts in practice.
Before we wind down here, it's worth mentioning that all these low-level APIs, such as wait(), notify() and notifyAll() – are traditional methods that work well, but higher-level mechanism are often simpler and better – such as Java's native Lock and Condition interfaces (available in java.util.concurrent.locks package).
สำหรับข้อมูลเพิ่มเติมเกี่ยวกับแพ็คเกจjava.util.concurrentโปรดไปที่ภาพรวมของบทความ java.util.concurrent ของเราและการล็อกและเงื่อนไขอยู่ในคู่มือสำหรับ java.util.concurrent.Locks ที่นี่
เช่นเคยข้อมูลโค้ดทั้งหมดที่ใช้ในบทความนี้มีอยู่ใน GitHub