• Welcome to the world's largest Chinese hacker forum

    Welcome to the world's largest Chinese hacker forum, our forum registration is open! You can now register for technical communication with us, this is a free and open to the world of the BBS, we founded the purpose for the study of network security, please don't release business of black/grey, or on the BBS posts, to seek help hacker if violations, we will permanently frozen your IP and account, thank you for your cooperation. Hacker attack and defense cracking or network Security

    business please click here: Creation Security  From CNHACKTEAM

"生产者-消费者"模型(2021-11-29)


Recommended Posts

对象类的方法:等待等待(),唤醒队首线程通知(),唤醒全部等待线程notifyAll()。利用等待和唤醒实现生产者线程、消费者线程的互斥访问消息对象。

代码如下:

包线程演示

类别消息{

私有字符串消息="";

私有布尔标志=true//记录型信号量,规定真实的表示没有消息(允许生产、不许消费),假的表示已有消息(不许生产、允许消费)

公共同步void setMessage(字符串消息){

if(flag==false) {

尝试{

超级棒。wait();//不许生产、让生产者线程等待

} catch (InterruptedException e) {

e。printstacktrace();

}

}

尝试{

线程。睡眠(100);

} catch (InterruptedException e) {

e。printstacktrace();

}

this.msg=味精

flag=false//生产完成,改变信号量、唤醒消费者

超级棒。notify();

}

公共同步字符串getMessage() {

if(flag==true) {

尝试{

超级棒。wait();//不许消费、让消费者线程等待

} catch (InterruptedException e) {

e。printstacktrace();

}

}

尝试{

线程。睡眠(100);

} catch (InterruptedException e) {

e。printstacktrace();

}

尝试{

返回msg=' this.msg

}

最后{//返回后用最后确保指令执行

flag=true//消费完成,改变信号量、唤醒生产者

超级棒。notify();

}

}

}

类生成器实现可运行{

私信味精

公共生产者(消息消息){

this.msg=味精

}

@覆盖

公共无效运行(){

for(int x=0;x30x ) {

if(x%2==0) {

msg.setMessage('夏天,穿短袖短裤');

}

否则{

msg.setMessage('冬天,换秋衣秋裤');

}

}

}

}

类使用者实现可运行{

私信味精

公共消费者(消息消息){

this.msg=味精

}

@覆盖

公共无效运行(){

for(int x=0;x30x ) {

系统。出去。println(消息。getmessage());

}

}

}

公共类主要{

公共静态void main(String[] args){

Message msg=new Message();

新线程(新生产者(味精).start();//启动生产者线程

新线索(新消费者(味精).start();//启动消费者线程

}

}

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now