一. 实现两个线程。轮流打印出数字。例如以下:

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个线程轮流打印数字的问题的更多相关文章

  1. java启动3个线程轮流打印数字

    转自:http://blog.csdn.net/u014011112/article/details/50988769 http://blog.csdn.net/perrywork/article/d ...

  2. Java多个线程顺序打印数字

    要求 启动N个线程, 这N个线程要不间断按顺序打印数字1-N. 将问题简化为3个线程无限循环打印1到3 方法一: 使用synchronized 三个线程无序竞争同步锁, 如果遇上的是自己的数字, 就打 ...

  3. 如何控制Java中的线程,总结了3种方法...

    问题:利用Java多线程,轮流打印数字,也就是怎么控制线程.... 1:通过synchronized的关键字,对类的static final 成员进行Lock,锁住对象,来实现同步. private ...

  4. 使用Java线程并发库实现两个线程交替打印的线程题

    背景:是这样的今天在地铁上浏览了以下网页,看到网上一朋友问了一个多线程的问题.晚上闲着没事就决定把它实现出来. 题目: 1.开启两个线程,一个线程打印A-Z,两一个线程打印1-52的数据. 2.实现交 ...

  5. 使用Java实现三个线程交替打印0-74

    使用Java实现三个线程交替打印0-74 题目分析 三个线程交替打印,即3个线程是按顺序执行的.一个线程执行完之后,唤醒下一个线程,然后阻塞,等待被该线程的上一个线程唤醒.执行的顺序是一个环装的队列 ...

  6. 使用Java 多线程编程 让三个线程轮流输出ABC,循环10次后结束

    简要分析: 要求三个线程轮流输出,这里我们要使用一个对象锁,让关键部分的代码放入同步块当中.同时要有一个变量记录打印的次数到达10次循环后不再打印,另外一个就是要给每个线程一个标志号,我们根据标识号来 ...

  7. Java线程同步打印ABC

    需求: 三个线程,依次打印ABCABCABC.... 方案一: 使用阻塞队列,线程1从队列1获取内容打印,线程2从队列2获取内容打印,线程3从队列3中获取内容打印.线程1把B放到队列3中,线程2把C放 ...

  8. java实现第七届蓝桥杯打印数字

    打印数字 打印数字 小明写了一个有趣的程序,给定一串数字. 它可以输出这串数字拼出放大的自己的样子. 比如"2016"会输出为: 00000 1 6666 2 0 0 1 1 6 ...

  9. Java 四种线程池newCachedThreadPool,newFixedThreadPool,newScheduledThreadPool,newSingleThreadExecutor

    介绍new Thread的弊端及Java四种线程池的使用,对Android同样适用.本文是基础篇,后面会分享下线程池一些高级功能. 1.new Thread的弊端执行一个异步任务你还只是如下new T ...

随机推荐

  1. .NET 开发者必备的工具箱

    本文作者Spencer是一名专注于ASP.NET和C#的程序员,他列举了平时工作.在家所使用的大部分开发工具,其中大部分工具都是集中于开发,当然也有一些其它用途的,比如图片处理.文件压缩等. 如果你是 ...

  2. javascript设计模式-掺元类

    有一种重用代码的方法不需要用到严格的继承.如果想把一个函数用到多个类中,可以通过扩充的方式让这些类共享该函数.其实际做法大大体为:先创建一个包含各种通用方法的类,然后再用它扩充其他的类.这种方式就叫做 ...

  3. js例子

    1.子菜单下拉 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www ...

  4. 46.Qt 使用OpenGL绘制立方体

    main.cpp #include <QApplication> #include <iostream> #include "vowelcube.h" in ...

  5. 如何运用docker配合python开发

    在网络层,互联网提供所有应用程序都要使用的两种类型的服务,尽管目前理解这些服务的细节并不重要,但在所有TCP/IP概述中,都不能忽略他们: 无连接分组交付服务(Connectionless Packe ...

  6. JqGrid saveRow方法报404错误

    TCX_1807工艺配置/检测项配置页面为jqgrid可编辑页面,使用的脚本为 ){ jQuery('#gridList').saveRow(lastId, true);//保存上一个修改的单元行 } ...

  7. hdu3938 Portal 离线的并查集

    离线算法是将全部输入都读入,计算出所有的答案以后再输出的方法.主要是为避免重复计算.类似于计算斐波那契数列的时候用打表的方法. 题目:给一个无向图,求有多少个点对,使得两点间的路径上的花费小于L,这里 ...

  8. winform右键菜单

    public partial class Form1 : Form { ContextMenuStrip cms; Bitmap bm ; public Form1() { InitializeCom ...

  9. CUDA5.5入门文章:VS10设置

    原文链接:http://blog.csdn.net/augusdi/article/details/12205435 作者专栏:http://blog.csdn.net/augusdi/article ...

  10. WebLogic安装使用及常见问题

    WebLogic的下载与安装 下载地址: http://www.oracle.com/technetwork/middleware/weblogic/downloads/index.html fmw_ ...