黑马程序员_多线程间通讯

线程间通讯

 

class Rec
{
	String name;
	String sex;
}
class Input implements Runnable
{
	private Rec r;
	Input(Rec r)
	{
		this.r = r;
	}
	public void run()
	{
		int x = 0
		while(true)
		{
			if(x = 0)
			{
				r.name = "milk";
				r.sex = "man";
			}
			else
			{
				r.name = "露丝";
				r.sex = "女";
			}
			x = (x+1)%2;
		}
	}
}
class Output implements Runnable
{
	private Rec;
	Output(Rec r)
	{
		this.r = r;
	}
	public void run()
	{
		while(true)
		{
			System.out.println(r.name+"…."+r.sex);
		}
	}
}
class Test
{
	public static void main(String[] args)
	{
		Rec r = new Rec();
		Input in = new Input(r);
		Output out = new Output(r);
		Thread t1 = new Thread(in);
		Thread t2 = new Thread(out);<pre class="java" name="code">		t1.start();
		t2.start();
	}
}
 

 


线程间实现了通讯,但是不安全

 

线程间通讯-解决安全问题

 

class Input implements Runnable
{
	private Rec r;
	Input(Rec r)
	{
		this.r = r;
	}
	public void run()
	{
		int x = 0
		while(true)
		{
			synchronized(r)
			{
				if(x = 0)
				{
					r.name = "milk";
					r.sex = "man";
				}
				else
				{
					r.name = "露丝";
					r.sex = "女";
				}
			}
			x = (x+1)%2;
		}
	}
}
class Output implements Runnable
{
	private Rec;
	Output(Rec r)
	{
		this.r = r;
	}
	public void run()
	{
		while(true)
		{
			synchronized(r)
				System.out.println(r.name+“….”+r.sex);
		}
	}
}


多线程-等待唤醒机制


class Rec
{
       	String name;
       	String sex;
       	boolean flag = false;
}
 
class Input implements Runnable
{
       	private Rec r;
       	Input(Rec r)
	{
       		this.r = r;
	}
	public void run()
	{
       		int x = 0
       		while(true)
		{
       			synchronized(r)
			{
       				if(r.flag)
              				try{r.wait();}catch(Exceptione){}
              			if(x = 0)
				{
              				r.name = “milk”;
              				r.sex = “man”;
				}
				else
				{
              				r.name = "露丝";
              				r.sex = "女";
				}
				r.flag = true;
       				r.notify();
                     	}
			x = (x+1)%2;
		}
	}
}<pre class="java" name="code">class Output implements Runnable
{
	private Rec;
	Output(Rec r)
	{
		this.r = r;
	}
	public void run()
	{
		while(true)
		{
			synchronized(r)
				if(!r.flag)//因为是同一把锁,因此上面是false,wait,下面则要取反值
					try{r.wait();}catch(Exception e){}
			System.out.println(r.name+“….”+r.sex);
			r.flag = false;
				r.notify();
		}
	}
}

 
  

代码优化

 

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

class Input implements Runnable
{
	private Rec r;
	Input(Rec r)
	{
		this.r = r;
	}
	public void run()
	{
		int x = 0
		while(true)
		{
			if(x = 0)
				r.set("milk","man");
			else
				r.set("露丝","女");
			x = (x+1)%2;
		}
	}
}
class Output implements Runnable
{
	private Rec;
	Output(Rec r)
	{
		this.r = r;
	}
	public void run()
	{
		while(true)
		{
			r.out();
		}
	}
}


线程间通讯-生产者消费者

class Resource
{
	private String name;
	private int count = 1;
	private boolean flag = false;
	
	public synchronized void set(String name)
	{
		while(flag)
			try{wait();}catch(Exception e){}
		this.name = name+"--"+count++);
		System.out.println(Thread.currentThread().getName +" ……生产者……"+ths.name);
		this.flag = true;
			this.notifyAll();
	}
	pubic synchronized void out()
	{
		while(!flag)
			try{wait();}catch(Exception e){}
		System.out.println(Thread.currentThread().getName+"…...消费者………."+this.name);
		this.flag = false;
		this.notifyAll();
	}
}
class Producter implements Runnable
{
	private Resource  r;
	producter(Resource r)
	{
		this.r  = r;
	}
	public void run()
	{
		while(true)
		{
			r.set(product);
		}
	}
}
class Customer implements Runnable
{
	private Resource  r;
	Customer(Resource  r)
	{
		this.r = r;
	}
	public void run()
	{
		while(true)
		{
			r.out();
		}
	}
}
class Test
{
	public static void main(String[] args)
	{
		Resource  r = new Resource();
		Producter  p = new Producter(r);
		Customer  c = new Customer(r);
		Thread t1 = new Thread(p);
		Thread t2 = new Thread(p);
		Thread t3 = new Thread(c);
		Thread t4 = new Thread(c);
		t1.start();
		t2.start();
		t3.start();
		t4.start();
	}
}

线程间通讯-生产者消费者JDK5.0升级版

 

将同步synchronized替换成现实Lock操作

将Object中的wait,notify,notifyAll,替换成Condition对象

该对象可以从Lock锁进行获取

该示例中,实现了本方只唤醒对方的操作

 

class Resource
{
	private String name;
	private int count = 1;
	private boolean flag = false;
	private Lock lock = new ReentrantLock();
	private Condition condition_pro = lock.newCondition();
	private Condition condition_con = lock.newCondition();
	public void set(String name)
	{
		try
		{
			lock.lock();
			while(flag)
				conditon_pro.await();
			this.name = name+"--"+count++);
			System.out.println(Thread.currentThread().getName+"…生产者……"+ths.name);
			this.flag = true;
				condition_con.signal();
		}
		finally
		{
			lock.unlock();
		}
	}
	pubic synchronized void out()
	{
		try
		{
			lock.lock();
			while(!flag)
				condition_con.await();
			System.out.println(Thread.currentThread().getName+"...消费者……"+this.name);
			this.flag = false;
				condition_pro.signal();
		}
		finally
		{
			lock.unLock();
		}
	}
}
class Producter implements Runnable
{
	private Resource  r;
	producter(Resource r)
	{
		this.r  = r;
	}
	public void run()
	{
		while(true)
		{
			r.set(product);
		}
	}
}
class Customer implements Runnable
{
	private Resource  r;
	Customer(Resource  r)
	{
		this.r = r;
	}
	public void run()
	{
		while(true)
		{
			r.out();
		}
	}
}
class Test
{
	public static void main(String[] args)
	{
		Resource  r = new Resource();
		Producter  p = new Producter(r);
		Customer  c = new Customer(r);
		Thread t1 = new Thread(p);
		Thread t2 = new Thread(p);
		Thread t3 = new Thread(c);
		Thread t4 = new Thread(c);
		t1.start();
		t2.start();
		t3.start();
		t4.start();
	}
}


停止线程

 

stop方法已经过时

如何停止线程

只有一种,run方法结束

开启多线程运行,运行代码通常是循环结构

只要控制住循环,就可以让run方法结束,也就是线程结束

 

特殊情况

当线程处于冻结状态

就不会读取到标记,那么线程就不会结束

 

当没有指定的方式让冻结的线程恢复到运行状态时,这时需要对冻结状态进行清除

强制让线程恢复到运行状态中来,这样就可以操作标记让线程结束

 

class StopThread implements Runnable
{
	private boolean flag = true;
	public synchronized void run()
	{
		while(flag)
		{
			try
			{
				wait();	
			}
			catch(InterruptedException e)
			{
				System.out.println("………..Exception");
				flag = false;
			}
			System.out.println("……..StopThread run…….");
		}
	}
	public void checkFlag()
	{
		this.flag = false;
	}
}
class Test
{
	public static void main(String[] args)
	{
		StopThread st = new StopThread();
		Thread t = new Thread(st);
		t.start();
		int x = 0;
		while(true)
		{
			if(x++ == 60)
			{
				t.interrupt();//叫醒冻结状态的线程并使他结束
				break;
			}
			System.out.println(Thread.currentThread()+"……main run…….."+x);
		}
	}
}


 

 

守护线程

将t标记为守护线程

 

class Test
{
	public static void main(String[] args)
	{
		StopThread st = new StopThread();
		Thread t = new Thread(st);
		t.setDaemon(true);//daemon:希腊神话中的守护神
		t.start();
		int x = 0;
		while(true)
		{
			if(x++ == 60)
			{
				t.interrupt();//叫醒冻结状态的线程并使他结束
				break;
			}
			System.out.println(Thread.currentThread()+"……main run…….."+x);
		}
	}
}


 

 

join方法

join:

当A线程执行到B线程的b.join()方法时,A就会等待,等B线程都执行完,A才会执行

 

霸道强势获取CUP的执行权使原本的线程处于冻结状态,例如主线程在执行过程中遇到Thread对象的join方法就会停止,等Thread对象执行完了之后在继续执行主线程

 

优先级&yield方法


setPriority():

设置线程的优先级

格式:线程对象.setPriority(Thread.MAX_PRIORITY)


 yield():

减缓线程的运行频率,使线程都能执行到,平均开来

Thread.yield();



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
资源包主要包含以下内容: ASP项目源码:每个资源包中都包含完整的ASP项目源码,这些源码采用了经典的ASP技术开发,结构清晰、注释详细,帮助用户轻松理解整个项目的逻辑和实现方式。通过这些源码,用户可以学习到ASP的基本语法、服务器端脚本编写方法、数据库操作、用户权限管理等关键技术。 数据库设计文件:为了方便用户更好地理解系统的后台逻辑,每个项目中都附带了完整的数据库设计文件。这些文件通常包括数据库结构图、数据表设计文档,以及示例数据SQL脚本。用户可以通过这些文件快速搭建项目所需的数据库环境,并了解各个数据表之的关系和作用。 详细的开发文档:每个资源包都附有详细的开发文档,文档内容包括项目背景介绍、功能模块说明、系统流程图、用户界面设计以及关键代码解析等。这些文档为用户提供了深入的学习材料,使得即便是从零开始的开发者也能逐步掌握项目开发的全过程。 项目演示与使用指南:为帮助用户更好地理解和使用这些ASP项目,每个资源包中都包含项目的演示文件和使用指南。演示文件通常以视频或图文形式展示项目的主要功能和操作流程,使用指南则详细说明了如何配置开发环境、部署项目以及常见问题的解决方法。 毕业设计参考:对于正在准备毕业设计的学生来说,这些资源包是绝佳的参考材料。每个项目不仅功能完善、结构清晰,还符合常见的毕业设计要求和标准。通过这些项目,学生可以学习到如何从零开始构建一个完整的Web系统,并积累丰富的项目经验。
黑马程序员多线程练习题主要包括两个问题。第一个问题是如何控制四个线程在打印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、付费专栏及课程。

余额充值