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 ...
随机推荐
- Android布局文件经验
1.父控件中含有多个子控件时.往往遵循长子优先的原则,即长子假设非常大可能占满父空间.使次子们出局: 2.如果TableLayout有2行,当中一行未设定列间长度比例.而还有一行设定了,则未设定行可能 ...
- 软件开发 —— 重构(refactor)
0. 代码坏味道 Large Class,过大的类:Large method,过长的(成员)函数: 1. 基本内涵 在不改变代码外在行为的前提下对代码做出修改,以改进代码的内部结构的过程. -- &l ...
- 部署hexo后github pages页面未更新或无法打开问题
title: 部署hexo后github pages页面未更新或无法打开问题 date: 2018-03-30 15:34:29 categories: methods tags: hexo gith ...
- Svn install and use
1.安装服务 使用yum安装subversion,简单.不繁琐. 1 yum install -y subversion 2.创建版本库 1 2 mkidr /svn/obj ...
- SDAutoLayout的使用
## 简介- IOS布局的三个阶段:MagicNumber -> AutoResizingMask -> AutoLayout- 自动布局三大框架:UILayoutConstraint(原 ...
- SQL学习整理
SQL整理 SQL 对大小写不敏感! 一.对数据的操作 实现功能分类: 1. 增: 1.1 表存在,插入栏位: //插入新的行(按栏位的顺序插入) INSERT INTO Table_1 VALUES ...
- 使用DbVisualizer变量
变量可用于构建参数化SQL语句,并让DbVisualizer在执行SQL时提示您输入值.如果您重复执行相同的SQL,只是希望在同一个SQL语句中传递新数据,这很方便. 变量语法 变量格式支持设置默认值 ...
- nodeJs配置相关以及JSON.parse
nodeJs配置相关 实际上说应用相关更好吧,我不是很懂. 今天在工作中,被同事解决了一个问题,虽然多花了一些额外时间,但长痛不如短痛嘛 实际上的问题就是npm run target等命令可以,但是n ...
- 基于Nginx服务的用户认证
通过Nginx实现web页面的用户认证,用户名为:admin,密码为:654321 1.修改Nginx配置文件 # vim /usr/local/nginx/conf/nginx.conf ..... ...
- selenium的显示等待和隐式等待区别
1.selenium的显示等待 原理:显式等待,就是明确的要等到某个元素的出现或者是某个元素的可点击等条件,等不到,就一直等,除非在规定的时间之内都没找到,那么就跳出Exception.(简而言之:就 ...