博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java 多线程(生产者消费者)
阅读量:6853 次
发布时间:2019-06-26

本文共 1411 字,大约阅读时间需要 4 分钟。

转 https://www.oschina.net/code/snippet_111708_25438

这个问题挺经典,我这个解法的本质在于将问题抽象为生产者消费者模型,但是是一个特殊的生产者消费者模型,有两点要求:

1、缓冲区大小为1(用一个布尔变量表示就可以了)
2、缓冲区初始为空
再具体点可以将其想象为一个一次只能放一张纸打印的打印机,放纸的线程是A,打印的线程是B。初始状态打印机没有纸。

// 打印机类
public
class
Printer {
     
    
private
boolean
hasBufferToPrint =
false
;  
// 打印缓冲区是否有内容可以打印
 
    
// 打印A:相当于生产者,放一张纸
    
public
synchronized
void
printA() {
        
while
(hasBufferToPrint) {  
// 缓冲区还有内容
            
try
{
                
wait();
            
}
catch
(InterruptedException e) {
                
e.printStackTrace();
            
}
        
}
         
        
System.out.print(
"A"
);
        
hasBufferToPrint =
true
;
         
        
notify();  
// 唤醒打印B的线程
    
}
     
    
// 打印B:相当于消费者,消耗缓冲区中的纸,打印纸张
    
public
synchronized
void
printB() {
        
while
(!hasBufferToPrint) {
            
try
{
                
wait();
            
}
catch
(InterruptedException e) {
                
e.printStackTrace();
            
}
        
}
         
        
System.out.print(
"B"
);
        
hasBufferToPrint =
false
;
         
        
notify();  
// 唤醒打印A的线程
    
}
 
    
static
class
ThreadA
extends
Thread {
        
private
Printer printer;
 
        
public
ThreadA(Printer printer) {
            
this
.printer = printer;
        
}
 
        
public
void
run() {
            
for
(
int
i =
0
; i <
10
; i++) {
                
printer.printA();
            
}
        
}
    
}
 
    
static
class
ThreadB
extends
Thread {
        
private
Printer printer;
         
        
public
ThreadB(Printer printer) {
            
this
.printer = printer;
        
}
         
        
public
void
run() {
            
for
(
int
i =
0
; i <
10
; i++) {
                
printer.printB();
            
}
        
}
    
}
 
    
public
static
void
main(String args[]) {
        
Printer printer =
new
Printer();  
// A、B线程共享同一个打印机
        
Thread a =
new
ThreadA(printer);
        
Thread b =
new
ThreadB(printer);
         
        
a.start();
        
b.start();
    
}
}

转载于:https://www.cnblogs.com/elenz/p/6849700.html

你可能感兴趣的文章
记一次基于vue-cli的多页面应用配置
查看>>
适用于小程序的 ES6
查看>>
Ribbon使用方法
查看>>
【译】将 Android 项目迁移到 Kotlin 语言
查看>>
vue 项目打包部署,通过nginx 解决跨域问题
查看>>
LightKV-高性能key-value存储组件
查看>>
小程序
查看>>
ES6变量的解构赋值
查看>>
ansible自动化运维详细教程及playbook详解
查看>>
快速解决Dev c++无法调试
查看>>
自学算法笔记
查看>>
python通过luhn算法实现的信用卡卡号验证源码
查看>>
小米手机5X获得Root权限的方法
查看>>
中国联通把百度指向了127.0.0.1?
查看>>
Java程序员这样优化简历,一投制胜!
查看>>
runtime(消息转发)
查看>>
设计模式——建造者模式
查看>>
Async & generator & Promise
查看>>
解决vagrant ssh登录时permission deny的问题
查看>>
Dapper,大规模分布式系统的跟踪系统
查看>>