欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

关于多线程的一道题目 博客分类: java 试题

程序员文章站 2024-03-11 13:33:37
...

题目大意:有四个线程,每个线程输出1,2,3,4,设计程序使得依次输出:1111222233334444

 

求解思路:创建一个对象o,当四个线程依次输出1后,检测已经输出的次数count,如果输出次数为1,2,3,那么让线程进入对象o的等待集,如果为4,那么唤醒o中等待集中所有线程并将count重置。

 

public class PrintTest extends Thread {
	public static Object o=new Object();
	public static int count=0;
	private int num=0;
	
	public void run(){
		synchronized(o){
		    while(num<4){
		        System.out.println(num+1);
			    if(count<2){
			        count++;
			        try {
						o.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
			    }else{
				    count=0;
				    o.notifyAll();
			    }
		    }
	    }
	}
	
	public static void mian(String[] args){
		for(int i=0;i<4;i++){
			new PrintTest().start();
		}
	}

}

 输出:1111222233334444

相关标签: 试题