黑马程序员——多线程(线程间通信)


-----------android培训java培训、java学习型技术博客、期待与您交流!------------


线程间通讯:

其实就是多个线程在操作同一个资源。

但是操作的动作不同。


程序:

线程交替执行。


class Res
{
	String name;
	String sex;
	boolean flag = false;
}

class Input implements Runnable
{
	private Res r;
	Input(Res r)
	{
		this.r = r;
	}
	public void run()
	{
		int x =0;
		
		while(true)
		{
			synchronized (r) {
				if(!r.flag)
				{
					if (x == 0) {
						r.name = "mike";
						r.sex = "man";
					} else {
						r.name = "丽丽";
						r.sex = "女女";
					}
					System.out.println("Input....."+r.name + "....." + r.sex);
					x=(x+1)%2;
					r.flag=true;
				}
			}
		}
	}
}

class Output implements Runnable
{
	private Res r;
	Output(Res r)
	{
		this.r = r;
	}
	public void run()
	{
		while(true)
		{
			synchronized (r) {
				if(r.flag)
				{
					System.out.println("Output....."+r.name + "....." + r.sex);
					r.flag=false;
				}
				
			}
		}
	}
}


public class InputOutputDemo {

	public static void main(String[] args) 
	{
		Res r = new Res();
		Input in = new Input(r);
		Output out = new Output(r);
		
		Thread t1 = new Thread(in);
		Thread t2 = new Thread(out);
		
		t1.start();
		t2.start();
	}

}

利用等待唤醒机制是线程交替执行:


class Res
{
	String name;
	String sex;
	boolean flag = false;
}

class Input implements Runnable
{
	private Res r;
	Input(Res r)
	{
		this.r = r;
	}
	public void run()
	{
		int x =0;
		
		while(true)
		{
			synchronized (r) {
				if(r.flag)
					try {
						r.wait();
					} catch (InterruptedException e) {
						// TODO 自动生成的 catch 块
						e.printStackTrace();
					}
				    if (x == 0) {
						r.name = "mike";
						r.sex = "man";
					} else {
						r.name = "丽丽";
						r.sex = "女女";
					}
					System.out.println("Input....."+r.name + "....." + r.sex);
					x=(x+1)%2;
					r.flag=true;
					r.notify();
			}
		}
	}
}

class Output implements Runnable
{
	private Res r;
	Output(Res r)
	{
		this.r = r;
	}
	public void run()
	{
		while(true)
		{
			synchronized (r) {
				if(!r.flag)
					try {
						r.wait();
					} catch (InterruptedException e) {
						// TODO 自动生成的 catch 块
						e.printStackTrace();
					}
					System.out.println("Output....."+r.name + "....." + r.sex);
					r.flag=false;
				    r.notify();
				
			}
		}
	}
}


public class InputOutputDemo {

	public static void main(String[] args) 
	{
		Res r = new Res();
		Input in = new Input(r);
		Output out = new Output(r);
		
		Thread t1 = new Thread(in);
		Thread t2 = new Thread(out);
		
		t1.start();
		t2.start();
	}

}

   wait();

notify();

notifyAll();

都使用在同步中,因为要对持有监视器(锁)的线程操作。

所以要使用在同步中,因为只有同步才具有锁。


为什么这些操作线程的方法要定义Object类中?

因为这些方法在操作同步中的线程时,都必须要标识它们所操作线程的锁。

只有同一个锁上的被等待线程,可以被同一个锁上的notify唤醒。

不可以对不同锁中的线程进行唤醒。

也就是说,等待和唤醒必须是同一个锁。

而锁可以是任意对象,所以可以被任意对象调用的方法定义在Object类中。


代码优化:


class Res
{
	private String name;
	private String sex;
	private boolean flag = false;
	
	public synchronized void getNameAndSex() 
	{
			if(!flag)
				try {this.wait();} catch (Exception e) {}
			System.out.println( name+"........."+sex+this+"......."+this.getClass());
			flag = false;
			this.notify();
	}
	
	public synchronized  void setNameAndSex(String name,String sex) 
	{
			if(flag)
				try {this.wait();} catch (Exception e) {}
			this.name = name;
			this.sex = sex;
			flag = true;
			this.notify();
	}
}

class Input implements Runnable
{
	private Res r;
	Input(Res r)
	{
		this.r = r;
	}
	public void run()
	{
		int x =0;
		while(true)
		{
			if (x == 0) 
				r.setNameAndSex("mike","man") ;
			else 
				r.setNameAndSex("丽丽","女女") ;
		    x=(x+1)%2;	    
		}
	}
}

class Output implements Runnable
{
	private Res r;
	Output(Res r)
	{
		this.r = r;
	}
	public void run()
	{
		while(true)
		{
		    r.getNameAndSex();
		}
	}
}


public class InputOutputDemo {

	public static void main(String[] args) 
	{
		Res r = new Res();
		new Thread(new Input(r)).start();
		new Thread(new Output(r)).start();
		/*
		Input in = new Input(r);
		Output out = new Output(r);
		
		Thread t1 = new Thread(in);
		Thread t2 = new Thread(out);
		
		t1.start();
		t2.start();
		*/
	}

}

注意:

this为类的地址,this.getclass()为本类的类型。


多个生产者和消费者

多于多个生产者和消费者。

为什么要定义while判断标记。

原因:让被唤醒的线程再一次判断标记。


为什么定义notifyAll?

因为需要唤醒对方线程。

因为只用notify,容易出现只唤醒本方线程的情况。导致程序中所有线程都等待。




public class ProducerConsumerDemo 
{

	public static void main(String[] args) 
	{
		Resource r = new Resource();
		Producer pro = new Producer(r);
		Consumer con = new Consumer(r);
		
		Thread t1 = new Thread(pro);
		Thread t2 = new Thread(pro);
		Thread t3= new Thread(con);
		Thread t4 = new Thread(con);
		
		t1.start();
		t2.start();
		t3.start();
		t4.start();
	}

}

class Resource
{
	private String name;
	private int count = 1;
	private boolean flag = false;
	
	public synchronized void set(String name)
	{
		while(flag)
			try {this.wait();} catch (InterruptedException e) {}
		this.name = name + "__"+count++;
		System.out.println(Thread.currentThread().getName()+"...生产者.."+this.name);
		flag = true;
		this.notifyAll();
	}
	public synchronized void out()
	{
		while(!flag)
			try {this.wait();} catch (InterruptedException e) {}
		System.out.println(Thread.currentThread().getName()+"...消费者......"+this.name);
		count--;
		flag = false;
		this.notifyAll();
	}
}

class Producer implements Runnable
{
	private Resource res;
	
	Producer(Resource res)
	{
		this.res = res;
	}
	public void run()
	{
		while(true)
		{
			res.set("+商品+");
		}
	}
}

class Consumer implements Runnable
{
	private Resource res;
	Consumer(Resource res)
	{
		this.res = res;
	}
	public void run()
	{
		while(true)
		{
			res.out();
		}
	}
}


-----------android培训java培训、java学习型技术博客、期待与您交流!------------

黑马程序员多线程练习题主要包括两个问题。第一个问题是如何控制四个线程在打印log之前能够同时开始等待1秒钟。一种解决思路是在线程的run方法中调用parseLog方法,并使用Thread.sleep方法让线程等待1秒钟。另一种解决思路是使用线程池,将线程数量固定为4个,并将每个调用parseLog方法的语句封装为一个Runnable对象,然后提交到线程池中。这样可以实现一秒钟打印4行日志,4秒钟打印16条日志的需求。 第二个问题是如何修改代码,使得几个线程调用TestDo.doSome(key, value)方法时,如果传递进去的key相等(equals比较为true),则这几个线程应互斥排队输出结果。一种解决方法是使用synchronized关键字来实现线程的互斥排队输出。通过给TestDo.doSome方法添加synchronized关键字,可以确保同一时间只有一个线程能够执行该方法,从而实现线程的互斥输出。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [黑马程序员——多线程10:多线程相关练习](https://blog.csdn.net/axr1985lazy/article/details/48186039)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值