博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
生产者和消费者
阅读量:3960 次
发布时间:2019-05-24

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

public class Comuser {
public static void main(String[] args) {
Data data = new Data(); new Thread(()->{
for (int i = 0; i < 20; i++) {
data.decrement(); } },"顾客").start(); new Thread(()->{
for (int i = 0; i < 20; i++) {
data.increment(); } },"老板").start(); }}class Data{
private int number = 0; //+1 public synchronized void increment() {
//同步方法锁的就是this //有数据的时候就等待 if(number != 0) {
try {
this.wait(); } catch (InterruptedException e) {
e.printStackTrace(); } } number++; System.out.println(Thread.currentThread().getName()+"=>"+number); this.notify(); } //-1 public synchronized void decrement() {
//没有数据就等待 if(number == 0) {
try {
this.wait(); } catch (InterruptedException e) {
e.printStackTrace(); } } number--; System.out.println(Thread.currentThread().getName()+"=>"+number); this.notify(); }}

在这里插入图片描述

转载地址:http://dohzi.baihongyu.com/

你可能感兴趣的文章
转: 我的android studio学习日记
查看>>
Android_Note(三)——添加、更新、保存记事本功能
查看>>
Ruby 的 Test::Unit
查看>>
创建数据方法
查看>>
JUnit单元测试的几个规律总结
查看>>
QTP之网页链接
查看>>
Fiddler实用教程
查看>>
从入门到深入Fiddler (一)
查看>>
从入门到深入Fiddler (二)
查看>>
Win7+php7+apache2.4
查看>>
QTP基本使用——associate actions
查看>>
charAt()方法和charCodeAt()方法—— 从字符串中选取一个字符.
查看>>
(1)Pascal 程序结构和基本语句
查看>>
LoadRunner之——脚本分析
查看>>
Advanced searching - fields reference
查看>>
Advanced searching - operators reference
查看>>
LoadRunner之——Java vuser
查看>>
LoadRunner之——场景创建、设置、运行
查看>>
QTP基本使用——Recovery Scenarios
查看>>
Ruby 的优缺点
查看>>