打开APP
未登录
开通VIP,畅享免费电子书等14项超值服
开通VIP
首页
好书
留言交流
下载APP
联系客服
(柯昌合)启动三个线程A,B,C,打印10次 按照ABC的顺序输出(柯昌合)
大头祥子
>《JavaSE》
2014.02.11
关注
[java]
view plain
copy
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ABC5 {
private int cond = 1;// 通过cond来确定A B C的输出
private Lock lock = new ReentrantLock();// 通过JDK5中的锁来保证线程的访问的互斥
private Condition condition = lock.newCondition();// 线程协作
public static void main(String[] args) {
ABC5 abc = new ABC5();// 内部类线程执行方式jdk1.5
ThreadA ta = abc.new ThreadA();// 声明3个runnable类
ThreadB tb = abc.new ThreadB();
ThreadC tc = abc.new ThreadC();
ExecutorService executor = Executors.newFixedThreadPool(3);// 通过线程池执行
for (int i = 0; i < 10; i++) {
executor.execute(ta);
executor.execute(tb);
executor.execute(tc);
}
executor.shutdown();// 关闭线程池
}
class ThreadA implements Runnable {
public void run() {
lock.lock();
try {
while (true) {
if (cond % 3 == 1) {
System.out.print(cond+":A");
cond++;
condition.signalAll();
break;
} else {
try {
condition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
} finally {
lock.unlock();
}
}
}
class ThreadB implements Runnable {
public void run() {
lock.lock();
try {
while (true) {
if (cond % 3 == 2) {
System.out.print(cond+":B");
cond++;
condition.signalAll();
break;
} else {
try {
condition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
} finally {
lock.unlock();
}
}
}
class ThreadC implements Runnable {
public void run() {
lock.lock();
try {
while (true) {
if (cond % 3 == 0) {
System.out.println(cond+":C");
cond++;
condition.signalAll();
break;
} else {
try {
condition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
} finally {
lock.unlock();
}
}
}
}
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请
点击举报
。
打开APP,阅读全文并永久保存
查看更多类似文章
猜你喜欢
类似文章
【热】
打开小程序,算一算2024你的财运
柯以敏<想你想疯了>等(诺亚之方舟辑)
柯九思
柯九思:《秀石疏竹晚寂》
柯拉
2017,还是得好看下去
柯金胜
更多类似文章 >>
生活服务
热点新闻
留言交流
回顶部
联系我们
分享
收藏
点击这里,查看已保存的文章
导长图
关注
一键复制
下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!
联系客服
微信登录中...
请勿关闭此页面
先别划走!
送你5元优惠券,购买VIP限时立减!
5
元
优惠券
优惠券还有
10:00
过期
马上使用
×