多线程交替打印数字

最近面试,有一道题目:有3个线程,每个线程打印5个数字,线程0打印1 2 3 4 5 ,线程1打印 6 7 8 9 10,线程2打印 11 12 13 14 15 回到线程0 打印,3个线程循环,停止条件是:当值为75。

当时我是写了3个线程,通过使用线程的成员变量lock的wait和notify方法,达到线程中流程的停止和继续;当一个线程停止任务(打印完毕),就通知下一个线程;通知信息形成一个循环。

回来后,我觉得写的太笨重,不好维护和扩展。 
使用数组,链表这种数据结构,利用它的线性结构,每当一个元素执行完毕,就轮到下一个元素。元素只需完成自身的任务,不需要和其他元素沟通,解耦;扩展线程数量,只需增加元素个数。

下面就是我的实现代码。 
它实现了题目的功能,但是有以下缺点: 
1。数据结构使用的是数组,导致我要在迭代到最后一个元素时,手动回到第一个元素。改进:使用循环数组或者循环链表;

2。元素线程,在while循环中,不会停止。改进:当值满足条件后,要通知所有线程执行完毕,break迭代



import java.util.ArrayList;
import java.util.List;

public class AsePrint {
	protected static Integer value = 0;
	
	volatile public static boolean next = false;

	static Object lockObject = new Object();
	
	static boolean flag = true;

	private List<PrintThread> createThreadObject(int num) {
		List<PrintThread> list = new ArrayList<PrintThread>();
		PrintThread printThread = null;
		for (int i = 0; i < num; i++) {
			printThread = new PrintThread();
			list.add(printThread);
		}
		return list;
	}

	public static void main(String[] args) throws InterruptedException {
		// PrintThread printThread = new PrintThread();
		// printThread.start();
		AsePrint asePrint = new AsePrint();
		int threadNum = 3;
		List<PrintThread> list = asePrint.createThreadObject(threadNum);
		System.out.println(list);
		boolean first = true;
		for (int i = 0; value < 7500; i++) {
			if(first) {
				list.get(i).start();
			}			
			else {
				synchronized (list.get(i).lock) {
					list.get(i).lock.notify();
				}
			}
			while(!next) {
				Thread.sleep(1);
			}
			next = false;
			
			if (i == threadNum - 1) {
				i = -1;
				first = false;
			}
		}

	}
}

class PrintThread extends Thread {
	public Object lock = new Object();
	
	public void run() {
		while(true) {
		for (int i = 1; i <= 5; i++) {
			synchronized (AsePrint.value) {
				++AsePrint.value;
				System.out.println(Thread.currentThread().getName() + " " + AsePrint.value);
			}
		}
			AsePrint.next = true;
			System.out.println(AsePrint.next);
			synchronized (lock) {
				try {
					lock.wait();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		
	}
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值