Typical Example of Java thread learning-reader demonstration
Typical Example of Java thread learning-reader demonstration
The most typical example of Java Thread learning-the reader, mainly uses the Thread knowledge as follows:
-Thread start and run
-Sleep)
-Synchronized)
-Wait and release of Data Objects (wait and notify)
Program Implementation:
-ObjectData objects are locked by using the synchronized keyword and used by the thread reader.
-ConsumerThread: the consumer thread that notifies the producer thread after reading the count value in the Data Object
-ProductThread: The producer thread that operates on the count value of the data object, adds 1 each time, and then notifies the consumer thread
The class structure is as follows:
Code Implementation
Consumer-read thread
package com.gloomyfish.jse.thirdteen;public class ConsumerThread extends Thread {private ObjectData data;public ConsumerThread(ObjectData data) {this.data = data;}@Overridepublic void run() {while(true) {try {synchronized (data) {data.wait();data.read();data.notify();}} catch (InterruptedException e) {e.printStackTrace();}}}}
Write thread-producer thread
package com.gloomyfish.jse.thirdteen;public class ProductThread extends Thread {private ObjectData data;public ProductThread(ObjectData data) {this.data = data;}@Overridepublic void run() {while (true) {try {synchronized (data) {data.write();Thread.sleep(3000);data.notify();data.wait();}} catch (InterruptedException e) {e.printStackTrace();}}}}
Data Object Class
package com.gloomyfish.jse.thirdteen;public class ObjectData {private int count;public ObjectData() {count = 0;}public void read() {System.out.println("read count : " + count);System.out.println();}public void write() {count++;System.out.println("write count : " + count);}}
Test code:
public static void main(String[] args) {ObjectData data = new ObjectData();ConsumerThread ct = new ConsumerThread(data);ProductThread pt = new ProductThread(data);ct.start();pt.start();}
Summary:
The sample code completes how to read and write data between threads through wait and notify.
Synchronization Control. Demonstrate the usage of the synchronous keyword synchronized in Java and the usage of the thread.