黑马程序员——多线程学习笔记(二)

本文介绍Java中线程间的通信机制,包括通过共享资源实现线程间的数据传递和控制,以及如何利用生产者消费者模式解决多线程同步问题。文章详细解释了使用wait(), notify() 和 notifyAll() 方法的原理与应用,并展示了如何避免常见的线程安全问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

------- android培训java培训、期待与您交流! ----------

线程间通信:

其实就是多个线程在操作同一个资源,但是操作的动作不同。

class Res{
	String name;
	String sex;
	Boolean flag = false;//存取标志位。由于存储数据之后可以多次被取出,或者多次存储之后再被取出,因此需要标志位判断当前时刻是否应该存取。
}

class Input implements Runnable{
	private Res r;
	private obj ;//创建一个锁对象
	Input(Res r, Object obj){
		this.r = r;
		this.obj = obj;
	}

	public void run(){
		int x = 0;
		while(true){
			synchronized(obj){//可能出现安全问题:当Input执行到r.name=”mike”后(r.sex=”man”前),Output就开始打印了姓名和性别,因此出现了“人妖”,解决方式是将这两个线程添加同步。
				if(r.flag){//如果已经存在数据,则等待
					obj .wait();
				}
				
				if(x==0){
					r.name = “mike”;
					r.sex=”man”;
				}
				else{
					r.name=”丽丽”;
					r.sex = “女”;
				}
				x = (x+1)%2;
				r.flag = true;//存进数据后,将标记设置成true。
				obj .notify();//唤醒output线程。
			}
		}
	}
}

class Output implements Runnable{
	private Res r ;
	private Object obj;
	Output(Res r, Object obj){
		this.r = r;
		this.obj = obj;
	}
	public void run(){
		while(true){
			synchronized(obj){
				if(!r.flag){//判断是否已经存在数据,如果不存在,则等待。
					obj .wait();
				}
				System.out.println(r.name+”…”+ r.sex);
				r.flag = false;//取出数据后,设置标志位为false。
				obj .notify();唤醒input线程。
			}
		}
	}
}

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 Resource{
	private String name;
	private int count = 1;
	private Boolean flag = false;

	public synchronized void set(String name){
		while(flag){//当两个生产线程同时进入wait()时,if判断会造成被唤醒的生产线程不再判断,直接生产,最终造成了生产两次商品的问题。因此这里需要用while循环判断
			try{
				wait();
			}catch(Exception e){
			}
		}
		this.name = name+”--”+count++;
		System.out.println(Thread.currentThread().getName()+”…生产者..”+this.name);
		flag = true;
		this.notifyAll();//notify()方法会导致生产线程唤醒另一个生产线程,但是我们需要唤醒消费线程,因此需改为notifyAll(),唤醒全部线程。
	}
	public synchronized void out(){
		while (!flag){
			try{
				wait();
			}catch(Exception e){
			}
		}
		System.out.println(Thread. currentThread().getName()+”…消费者…..”+this.name);
		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 implement Runnable{
	private Resource res;

	Consumer (Resource res){
		this.res = res;
	}

	public void run(){
		while(true){
			res.out();
		}
	}
}

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();
		
	}
}

以上代码在使用notifyAll()方法时,目的是为了唤醒对方的线程,并不需要唤醒本方线程。在jdk1.5中提供了多线程升级解决方案,可以使用LockCondition接口提供的方法。将同步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 ReentratLock();//lock替代了synchronized功能,建立一个lock子类对象。

	private Condition condition_pro = lock.newCondition();//Condition替代了wait()、notify()、notifyAll()方法,从lock获取condition的对象。
	
	private Condition condition_con = lock.newCondition();

	public void set(String name) throws InterruptedException{//condition的方法需要抛异常
		lock.lock();//加锁
		while(flag){
			try{
				condition_pro.await();//生产者等待
				this.name = name+”--”+count++;
				System.out.println(Thread.currentThread().getName()+”…生产者..”+this.name);
				flag = true;
				condition_con.signal();//唤醒消费者
			}
			finally{
				lock.unlock();//释放锁,且一定要执行。
			}
		}
	}
	public void out() throws InterruptedException {
		lock.lock();
		try{
			while (!flag){
				condition_con.await();//消费者等待
			}
			System.out.println(Thread. currentThread().getName()+”…消费者…..”+this.name);
			flag = false;
			condition_pro.signal();//唤醒生产者
		}
		finally{
			lock.unlock();
		}
	}
}

class Producer implements Runnable{
	private Resource res;
	Producer(Resource res){
		this.res = res;
	}

	public void run(){
		while(true){
			try{
				res.set(“+商品+”);
			}
		}
	}
}

停止线程:

stop方法已经过时,停止线程的方式只有一种:run方法结束。

开启多线程运行,运行代码通常是循环结构。只要控制住循环,就可以让run方法结束,也就是线程结束。

class StopThread implements Runnable{
	private boolean flag = true;
	public void run(){
		while(flag){
			System.out.println(Thread.currentThread().getName()+”…run”);
		}
	}

	public void changeFlag(){
		flag = false;
	}
}

class StopThreadDemo{
	public static void main(String[] args){
		StopThread st = new StopThread();
		
		Thread t1 = new Thread(st);
		Thread t2 = new Thread(st);
		
		t1.start();
		t2.start();

		while(true){
			if(num++ == 60){
				st.changeFlag();
				break;
			}
			System.out.println(Thread.currentThread().getName()+”…...”+num);
		}
	}
}

 

特殊情况:、

当线程处于了冻结状态,就不会读取到标记,那么线程就不会结束。

当没有指定的方式让冻结的线程回复到运行状态时,这时需要对冻结状态进行清除。强制让线程回复到运行状态钟来,这样就可以操作标记让线程结束。

 

Thread类提供了该方法:interrupt();(使用该方法会使程序继续执行并抛出一个interruptedException异常,在catch块中接到,并写出令run方法结束的代码,即可结束线程。)

 

Thread其他常见方法:

setDaemon(Boolean on):将该线程标记为守护线程或用户线程。(当正在运行的线程都是守护线程时,JVM退出),该方法必须在启动线程前调用。

守护线程(后台线程):开启后和前台线程共同抢夺cpu执行权运行。当所有的前台线程都结束后,后台线程会自动结束。

 

join():A线程执行到了B线程的.join()方法时,那么A线程就会等待,等B线程都执行完,A才会执行,join可以用来临时加入线程执行。

class Demo implements Runnable{
	public void run(){
		for(int x= 0; x<70; x++){
			System.out.println(Thread.currentThread().getName()+”…..”+x);
		}
	}
}

class JoinDemo{
	public static void main(String[] args) throws Exception{
		Demo d= new Demo();
		Thread t1 = new Thread(d);
		Thread t2 = new Thread(d);

		t1.start();
		t1.join();//加入此代码后,结果为t1线程单独执行完毕后,其他线程才开始交替执行。因此join实际作用为抢夺cpu执行权,当主线程执行到此行代码时,把执行权放出,处于冻结状态,当			  //t1线程结束以后,主线程恢复运行状态。
		t2.start();

		for(int x = 0; x<80;x++){
			System.out.println(“main….”+x);
		}
		System.out.println(“over”);
	}
}

toString():返回线程名称、优先级和线程组。

*线程组:一般情况下,谁开启的这个线程,就属于谁的组(main线程中开启之后,线程组为main

*优先级:代表着抢资源的频率。所有线程默认优先级是5,可以用setPriority(int newPriority)方法修改,优先级范围为1-10。其中Thread类对1510三个优先级设置了常量,分别为:MIN_PRIORITYMAX_ PRIORITYNORM_ PRIORITY

 

yield():暂时释放执行权,稍微减少执行频率。达到线程都有机会平均运行的效果。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值