【Java】多线程

以:用线程同步处理的方法编写程序演示生产者和消费者模型 为例
代码:

package zhuabao;
class Share
{
	int contents;
	boolean available=false;
	public synchronized int get()
	{
		while(available==false)//对于进程,如果当前没有能够拿去的数据,处于停止状态
		{
			try {
				wait();
			}
			catch(Exception e) {
		}
	}
	available=false;//已经拿取过
	notifyAll();//释放对象锁,通知等待的线程重新占有锁并运行
	return contents;//得到内容
	}
	public synchronized void put(int value)
	{
		while(available==true)//记录的过程中,如果当前存放的数据没有被拿走,处于停止状态
		{
			try {
				wait();
			}
			catch(Exception e) {
		}
	}
	contents=value;//数据已经被拿走,放入新的数据
	available=true;//有新的数据,可以获取
	notifyAll();//释放对象锁,通知等待的线程重新占有锁并运行
	}
}
//生产者
class Customer extends Thread
{
	Share shared;//分享处理成员
	int number;
	public Customer(Share s,int number)
	{
		shared=s;
		this.number=number;
	}
	public void run()//顾客捕获获得数据并输出
	{
		int value=0;
		for(int i=0;i<10;i++)
		{
			value=shared.get();
			System.out.println("消费者"+this.number+"得到的数据:"+value);
		}
	}
}
class Producer extends Thread
{
	Share shared;//分享处理成员
	int number;//记录序号
	public Producer(Share s,int number)
	{
		shared=s;
		this.number=number;
	}
	public void run()//生产者不断得到数据
	{
		for(int i=0;i<10;i++)
		{
			shared.put(i);
			System.out.println("生产者"+this.number+"生产的数据:"+i);
		}
		try
		{
			sleep((int)Math.random()*100);
		}
		catch(Exception e) {
		}
	}
}
public class bao {
	public static void main(String []args)
	{
		Share s=new Share();
		Producer p=new Producer(s,1);
		Customer c=new Customer(s,1);
		p.start();
		c.start();
	}
}

运行结果:
在这里插入图片描述
在producer的run中插入断点
在这里插入图片描述
在消费者的run中插入断点

在这里插入图片描述
表明线程在运行的时候没有明显的先后关系(即使要求生产者在生产完10个数字之后说面0.1s),
并且因为有如下限制:
只有当前数据被取走之后才能生产下一个数据
消费者得到的数据一定是小于生产者生产的

关于sleep时间长短对于程序执行的影响

public class bao extends Thread
{
	static int total=10;
	int n;
	String name;
	public bao(int n,String name)
	{
		this.n=n;
		this.name=name;
	}
	public void run()
	{
		try
		{
			System.out.println(name);
			sleep(n);
			total+=n;
			System.out.println(total);
			System.out.println(n);
		}
		catch(Exception e)
		{
			System.out.println();
		}
	}
	public static void main(String[]args)
	{
		bao a1=new bao(3000,"A");
		bao a2=new bao(1000,"B");
		a1.start();
		a2.start();
	}
}

执行结果

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值