Today, a friend asked about the concept of Java multi-threading in the background. The editor thinks that only by mastering the basic thread concept can we have a deeper understanding of multi-threading. In layman's terms, it is multiple while loops running in parallel. If multiple things are done concurrently, multiple threads may operate on the same data block during actual use, so the problem of multi-threading arises. First, let’s understand the basic concepts of threads and simple code implementation
Classic examples of Java thread learning-reader and writer demonstration
The most classic example of Java thread learning-readers and writers, mainly using Thread related knowledge As follows:
-Thread start and run
-Thread sleep(sleep)
-Data object locking (synchronized)
-Data object Wait and release (wait and notify)
Program implementation:
-ObjectData data class object, locking is implemented through the synchronized keyword, and is used in thread readers and writers.
-ConsumerThread consumer thread, after reading the count value in the data object, notifies the producer thread
-ProductThread producer thread, operates on the count value in the data object, adding 1 each time, Then notify the consumer thread
The class structure diagram is as follows:
Code implementation
Consumer-reading thread
package com.gloomyfish.jse.thirdteen; public class ConsumerThread extends Thread { private ObjectData data; public ConsumerThread(ObjectData data) { this.data = data; } @Override public 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; } @Override public 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 program code is completed between threads How to realize data reading and writing through wait and notify
Synchronous control. Demonstrates the usage of Java's synchronization keyword synchronized and the usage of threads.
The above is the content of [java basics] thread instance. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!