Java線程學習經典例子-讀寫者演示
Java線程學習最經典的例子-讀寫者,主要用到Thread相關知識如下:
-線程的start與run
-線程的休眠(sleep)
-數據對象加鎖(synchronized)
-數據對象的等待與釋放(wait and notify)
程序實現:
-ObjectData數據類對象,通過synchronized關鍵字實現加鎖,在線程讀寫者中使用。
-ConsumerThread消費者線程,讀取數據對象中count值之後,通知生產者線程
-ProductThread生產者線程,對數據對象中count值操作,每次加1,然後通知消費者線程
類結構圖如下:
代碼實現
消費者-讀線程
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(); } } } }寫線程-生產者線程
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(); } } } }數據對象類
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); } }測試代碼:
public static void main(String[] args) { ObjectData data = new ObjectData(); ConsumerThread ct = new ConsumerThread(data); ProductThread pt = new ProductThread(data); ct.start(); pt.start(); }總結:
示例程序代碼完成了線程之間如何通過wait與notify實現數據的讀寫
同步控制。演示了Java的同步關鍵字synchronized的用法與線程的用法。