Java n个线程轮流打印数字的问题
一. 实现两个线程。轮流打印出数字。例如以下:
bThread --> 10
aThread --> 9
bThread --> 8
aThread --> 7
bThread --> 6
aThread --> 5
bThread --> 4
aThread --> 3
bThread --> 2
aThread --> 1
用java中的Lock类实现:
package com.yjq.thread_demo; import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock; public class TwoThreadPrinter { private Lock threadLock = new ReentrantLock(); private boolean flag = false; int count =10; Thread aThread = new Thread(new Runnable() {
public void run() {
while (true) {
// 锁定
threadLock.lock();
try {
if ( count < 1) {
return;
}
if (flag) {
// aThread的任务
System.out.println("aThread --> " + (count--));
flag = !flag;
}
} catch (Exception e) {
// TODO: handle exception
} finally {
// 释放锁
threadLock.unlock();
}
}
}
}); Thread bThread = new Thread(new Runnable() {
public void run() {
while (true) {
// 锁定
threadLock.lock();
try {
if ( count < 1) {
return;
}
if (!flag) {
// aThread的任务
System.out.println("bThread --> " + (count--));
flag = !flag;
}
} catch (Exception e) {
// TODO: handle exception
} finally {
// 释放锁
threadLock.unlock();
}
}
}
}); public void startTwoThread() {
aThread.start();
bThread.start();
} public static void main(String[] args) {
TwoThreadPrinter twoThreadPrinter = new TwoThreadPrinter();
twoThreadPrinter.startTwoThread();
} }
用synchronized实现:
package com.yjq.thread_demo; public class TwoThreadPrinter2 { private Object threadLock = new Object(); int count =10; Thread aThread = new Thread(new Runnable() {
public void run() {
while (true) {
// 锁定
synchronized (threadLock) {
if ( count < 1) {
return;
} // // aThread的任务
System.out.println("aThread --> " + (count--)); threadLock.notify();
try {
threadLock.wait();
} catch (Exception e) {
// TODO: handle exception
}
}
}
}
}); Thread bThread = new Thread(new Runnable() {
public void run() {
while (true) {
// 锁定
synchronized (threadLock) {
if ( count < 1) {
return;
} // // aThread的任务
System.out.println("bThread --> " + (count--)); threadLock.notify();
try {
threadLock.wait();
} catch (Exception e) {
// TODO: handle exception
}
}
}
}
}); public void startTwoThread() {
aThread.start();
bThread.start();
} public static void main(String[] args) {
TwoThreadPrinter twoThreadPrinter = new TwoThreadPrinter();
twoThreadPrinter.startTwoThread();
} }
用Lock类的方法比較easy理解。 lock() 和 unlock()之间的块是被锁定的
用synchronize的方法少用了个flag来标志轮到哪个线程来打印,这是由于线程锁的notifity( )方法会释放锁并唤醒其它线程 ,线程锁的wait( )方法则是释放锁并休眠当前线程,假设刚好仅仅有两个线程,那么自然就是開始还有一个线程而休眠本线程。
二.扩展到n个线程轮流打印数字的问题
n个线程轮流打印数字。用Lock类是比較easy扩展的
比方三个线程轮流打印数字
package com.myexample.test; import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock; public class ThreeThreadPrinter { private Lock threadLock = new ReentrantLock(); private int flag = 0; int count =10; Thread aThread = new Thread(new Runnable() {
public void run() {
while (true) {
// 锁定
threadLock.lock();
try {
if ( count < 1) {
return;
}
if (count%3 == 0 ) {
// aThread的任务
System.out.println("aThread --> " + count);
count--;
}
} catch (Exception e) {
// TODO: handle exception
} finally {
// 释放锁
threadLock.unlock();
}
}
}
}); Thread bThread = new Thread(new Runnable() {
public void run() {
while (true) {
// 锁定
threadLock.lock();
try {
if ( count < 1) {
return;
}
if (count%3 == 1 ) {
// aThread的任务
System.out.println("bThread --> " + count);
count--;
}
} catch (Exception e) {
// TODO: handle exception
} finally {
// 释放锁
threadLock.unlock();
}
}
}
}); Thread cThread = new Thread(new Runnable() {
public void run() {
while (true) {
// 锁定
threadLock.lock();
try {
if ( count < 1) {
return;
}
if (count%3 == 2 ) {
// aThread的任务
System.out.println("cThread --> " + count);
count--;
}
} catch (Exception e) {
// TODO: handle exception
} finally {
// 释放锁
threadLock.unlock();
}
}
}
}); public void startTwoThread() {
aThread.start();
bThread.start();
cThread.start();
} public static void main(String[] args) {
ThreeThreadPrinter twoThreadPrinter = new ThreeThreadPrinter();
twoThreadPrinter.startTwoThread();
} }
输出结果
bThread --> 10
aThread --> 9
cThread --> 8
bThread --> 7
aThread --> 6
cThread --> 5
bThread --> 4
aThread --> 3
cThread --> 2
bThread --> 1
Java n个线程轮流打印数字的问题的更多相关文章
- java启动3个线程轮流打印数字
转自:http://blog.csdn.net/u014011112/article/details/50988769 http://blog.csdn.net/perrywork/article/d ...
- Java多个线程顺序打印数字
要求 启动N个线程, 这N个线程要不间断按顺序打印数字1-N. 将问题简化为3个线程无限循环打印1到3 方法一: 使用synchronized 三个线程无序竞争同步锁, 如果遇上的是自己的数字, 就打 ...
- 如何控制Java中的线程,总结了3种方法...
问题:利用Java多线程,轮流打印数字,也就是怎么控制线程.... 1:通过synchronized的关键字,对类的static final 成员进行Lock,锁住对象,来实现同步. private ...
- 使用Java线程并发库实现两个线程交替打印的线程题
背景:是这样的今天在地铁上浏览了以下网页,看到网上一朋友问了一个多线程的问题.晚上闲着没事就决定把它实现出来. 题目: 1.开启两个线程,一个线程打印A-Z,两一个线程打印1-52的数据. 2.实现交 ...
- 使用Java实现三个线程交替打印0-74
使用Java实现三个线程交替打印0-74 题目分析 三个线程交替打印,即3个线程是按顺序执行的.一个线程执行完之后,唤醒下一个线程,然后阻塞,等待被该线程的上一个线程唤醒.执行的顺序是一个环装的队列 ...
- 使用Java 多线程编程 让三个线程轮流输出ABC,循环10次后结束
简要分析: 要求三个线程轮流输出,这里我们要使用一个对象锁,让关键部分的代码放入同步块当中.同时要有一个变量记录打印的次数到达10次循环后不再打印,另外一个就是要给每个线程一个标志号,我们根据标识号来 ...
- Java线程同步打印ABC
需求: 三个线程,依次打印ABCABCABC.... 方案一: 使用阻塞队列,线程1从队列1获取内容打印,线程2从队列2获取内容打印,线程3从队列3中获取内容打印.线程1把B放到队列3中,线程2把C放 ...
- java实现第七届蓝桥杯打印数字
打印数字 打印数字 小明写了一个有趣的程序,给定一串数字. 它可以输出这串数字拼出放大的自己的样子. 比如"2016"会输出为: 00000 1 6666 2 0 0 1 1 6 ...
- Java 四种线程池newCachedThreadPool,newFixedThreadPool,newScheduledThreadPool,newSingleThreadExecutor
介绍new Thread的弊端及Java四种线程池的使用,对Android同样适用.本文是基础篇,后面会分享下线程池一些高级功能. 1.new Thread的弊端执行一个异步任务你还只是如下new T ...
随机推荐
- C语言数组和函数实例练习(二)
1.C语言中不允许函数的嵌套定义,但可以使用函数的嵌套调用. 例1:输入4个整数,找出其中最大的数. #include <stdio.h> #include <stdlib.h> ...
- 关于PHP浮点数之 intval((0.1+0.7)*10) 为什么是7
PHP是一种弱类型语言, 这样的特性, 必然要求有无缝透明的隐式类型转换, PHP内部使用zval来保存任意类型的数值, zval的结构如下(5.2为例): struct _zval_struct { ...
- 数据库技术_Orcale技术(0002)_5分钟会用存储过程_存储过程实例
基础技术: 样例业务功能: 1.依据传入的类型A_TYPE联合查询PROCEDURE_TEST_A表.PROCEDURE_TEST_A_SUB表中的数据.并显示主要内容. 2.依据传入的类型A_TYP ...
- 【POJ 1703】 Find them,Catch them
[题目链接] http://poj.org/problem?id=1703 [算法] 并查集 + 拆点 [代码] #include <algorithm> #include <bit ...
- php 判断字符串包含中文(转)
$str = "测试中文"; echo $str; echo "<hr>"; //if (preg_match("/^[".ch ...
- [牛客挑战赛 30D] 小A的昆特牌 解题报告 (组合数学)
interlinkage: https://ac.nowcoder.com/acm/contest/375/D description: solution: 我们枚举步兵的数量$x$,还剩下$S-x$ ...
- 【Linux】YUM Repositories for CentOS, RHEL & Fedora Systems
这里是官方wiki:https://wiki.centos.org/AdditionalResources/Repositories 一.简介 YUM(Yellowdog Updater Modifi ...
- IO流读取文件内容时,出现空格的问题(未找到原因)
import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOExceptio ...
- lhgdialog.js弹出框
官方学习网址: http://www.lhgdialog.com/ 个人认为它的样式不太好调,除此之外它也是一款实用的弹出框,专业的用来提示文字,消息,按钮添加function().ifame: 以下 ...
- ansible usually
链接地址:https://my.oschina.net/kangvcar/blog/1830155