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类的方法比较容易理解, lock() 和 unlock()之间的块是被锁定的


用synchronize的方法少用了个flag来标志轮到哪个线程来打印,这是因为线程锁的notifity( )方法会释放锁并唤醒其他线程 ,线程锁的wait( )方法则是释放锁并休眠当前线程,如果刚好只有两个线程,那么自然就是开始另一个线程而休眠本线程。


二.扩展到n个线程轮流打印数字的问题


n个线程轮流打印数字,用Lock类是比较容易扩展的


比如三个线程轮流打印数字

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



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值