生產(chǎn)者與消費者模型
- 通過使用Object的wait(),notify()方法進行生產(chǎn)者與消費者模型中出現(xiàn)的數(shù)據(jù)同步與數(shù)據(jù)重復(fù)操作問題
- 示例
package design;
/**
* 生產(chǎn)者與消費者模型
*/
public class ProvideAndConsumer {
public static void main(String[] args) {
Data data = new Data();
new Thread(new Provider(data)).start();
new Thread(new Consumer(data)).start();
}
}
/**
* 數(shù)據(jù)類
*/
class Data{
private String title;
private Double price;
/**
* flag=true:可生產(chǎn),但不可消費
* flag=false:可消費但不可生產(chǎn)
*/
private boolean flag=true;
/**
* 使用同步方法保證數(shù)據(jù)同步,使用開關(guān)flag,解決數(shù)據(jù)重復(fù)操作問題
* @param title
* @param price
*/
public synchronized void set(String title,Double price) {
if(this.flag==false){
try {
super.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//延遲,以觀察
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.title=title;
this.price=price;
this.flag=false;
super.notify();
}
/**
* 使用同步方法保證數(shù)據(jù)同步,使用開關(guān)flag,解決數(shù)據(jù)重復(fù)操作問題
*/
public synchronized void get() {
if(this.flag==true){
try {
super.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//延遲,以觀察
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(this);
this.flag=true;
super.notify();
}
@Override
public String toString() {
return "Data{" +
"title='" + title + '\'' +
", price=" + price +
'}';
}
}
/**
* 生產(chǎn)者
*/
class Provider implements Runnable{
private Data data;
public Provider (Data data){
this.data=data;
}
@Override
public void run() {
for(int i =0;i<10;i++){
if(i %2==0){
this.data.set("Java",18.9);
}else{
this.data.set("Php",8.9);
}
}
}
}
/**
* 消費者
*/
class Consumer implements Runnable{
private Data data;
public Consumer (Data data){
this.data=data;
}
@Override
public void run() {
for(int i =0;i<10;i++){
this.data.get();
}
}
}
線程池
- 普通執(zhí)行線程池定義:
java.util.concurrent.ExecutorService
- 調(diào)度線程池:
java.util.concurrent.ScheuledExecutorService
- 線程池創(chuàng)建類:
java.util.concurrent.Executors
- 創(chuàng)建無大小限制的線程池:
public static ExecutorService newCachedThreadPool()
- 創(chuàng)建指定現(xiàn)成大小的線程池:
public static ExecutorService newFixedThreadPool(int nThreads)
- 創(chuàng)建單線程池:
public static ExecutorService newSingleThreadExecutor()
- 創(chuàng)建定時調(diào)度池:
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize)
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者