首页 > Java > java教程 > 正文

java中的Condition协作线程接口类

迷茫
发布: 2017-03-26 16:01:25
原创
2158 人浏览过

在Java的Condition接口中,存在的几个方法跟Synchronized中的wait(),waitall(),wait(time ^),这个几个方法一一对应起来,但是在Lock.newCondition()返回中可以指定指定的线程释放和等待资源。

请看【唤醒单个线程】实例:

package TestThread.TestCondition;

import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.*;

public class TestCondition {
	public static void main(String[] args) {
		ReentrantLock lock = new ReentrantLock();
		Condition condition = lock.newCondition();
		Test1 th1 = new Test1(lock, condition, "线程1");
		Test1 th2 = new Test1(lock, condition, "线程2");
		Test1 th3 = new Test1(lock, condition, "线程3");
		Test2 t2 = new Test2(condition, lock, "我是唤醒线程");
		th1.start();
		th2.start();
		th3.start();
		try {
			Thread.sleep(1000);
			t2.start();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

class Test1 extends Thread {
	private ReentrantLock lock;
	private Condition condition1;

	public Test1(ReentrantLock lock, Condition condition1, String name) {
		super(name);
		this.lock = lock;
		this.condition1 = condition1;
	}

	@Override
	public void run() {
		for (int i = 0; i < 10; i++) {
			try {
				lock.lock();// 加锁
				if (i == 5) {
					try {
						condition1.await();
						System.out.println(Thread.currentThread().getName() + "当前线程获取到的值为:++++++++++++" + i);
					} catch (InterruptedException e) {
						System.out.println(Thread.currentThread().getName() + ":线程被中断了!");
					}
				} else {
					System.out.println(Thread.currentThread().getName() + ":当前线程获取到的值为===》" + i);
				}
			} catch (Exception e) {
				System.out.println("系统发生异常!");
			} finally {
				lock.unlock();// 解锁
			}
		}
	}
}

class Test2 extends Thread {
	private Condition condition;
	public ReentrantLock lock;

	/**
	 * @param condition协作对象
	 * @param lock锁对象
	 * @param name线程名称
	 */
	public Test2(Condition condition, ReentrantLock lock, String name) {
		super(name);
		this.condition = condition;
		this.lock = lock;
	}

	@Override
	public void run() {
		try {
			lock.lock();// 加锁
			condition.signal();// 唤醒启动单个线程
			System.out.println(Thread.currentThread().getName() + ":已经唤醒了一个线程!");
		} catch (Exception e) {
			System.out.println(Thread.currentThread().getName() + ":线程挂了!");
		} finally {
			lock.unlock();// 解锁
		}
	}
}
登录后复制

 

运行结果:2017-03-2501:16:17

以上是java中的Condition协作线程接口类的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!