论坛首页 Java企业应用论坛

面试题多线程ABC顺序打印,不能使用sleep

浏览 21192 次
精华帖 (0) :: 良好帖 (1) :: 新手帖 (3) :: 隐藏帖 (0)
作者 正文
   发表时间:2011-03-22   最后修改:2011-03-22
public class Test {
	private final static String code = "ABC";
	private static int index = 0;
	
	private static class PrintThread extends Thread{
		public void run(){
			for(;;){
				synchronized (code) {
					if(index == 3*10) return;
					System.out.print(code.charAt(index++ % 3));	
				}
			}
		}
	}
    public static void main(String[] args) {
    	for(int i=0;i<3;i++){
    		new PrintThread().start();
    	}
    }
} 
0 请登录后投票
   发表时间:2011-03-31  
Semaphore比较靠谱。
0 请登录后投票
   发表时间:2011-04-02   最后修改:2011-04-02
public class TestThead {
	public static void main(String[] args) throws InterruptedException {
		String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // 随便改什么字符串
		int runCount = 500; // 任意次数
		int strLength = str.length();     //就计算一次长度,避免字符串长了以后,重复计算长度
		String[] strBuffer = new String[strLength * runCount]; // 字符串输出缓存
		Thread[] Ths = new Thread[strLength];
		for (int index = 0; index < strLength; index++) {
			Ths[index] = new Thread(new Runner(index, strBuffer, str, strLength, runCount));
			Ths[index].start();
		}
                //等待所有线程结束
		for (int index = 0; index < strLength; index++) {
			Ths[index].join();
		}
                //输出结果
		for (int i = 0; i < strBuffer.length; i++) {
			System.out.print(strBuffer[i]);
			if ((i + 1) % strLength == 0)
				System.out.println();
		}
	}
}

class Runner implements Runnable {
	String[] strBuffer;
	String str;
	int strLength;
	int index;
	int runCount;

	public Runner(int index, String[] strBuffer, String str, int strLength, int runCount) {
		this.index = index;
		this.runCount = runCount;
		this.strBuffer = strBuffer;
		this.str = str;
		this.strLength = strLength;
	}

	@Override
	public void run() {
		for (int i = 0; i < runCount; i++) {
			strBuffer[strLength * i + index] = String.valueOf(str.charAt(index));
		}
	}
}



空间换时间,无需加锁
我是一个JAVA初学者,就按照自己思路写了一个,跑了几下是没问题,不过因为水平有限,大家也给看看这有什么地方会有问题?
0 请登录后投票
   发表时间:2011-04-02   最后修改:2011-04-02
yangyi 写道
public class Test {
	private final static String code = "ABC";
	private static int index = 0;
	
	private static class PrintThread extends Thread{
		public void run(){
			for(;;){
				synchronized (code) {
					if(index == 3*10) return;
					System.out.print(code.charAt(index++ % 3));	
				}
			}
		}
	}
    public static void main(String[] args) {
    	for(int i=0;i<3;i++){
    		new PrintThread().start();
    	}
    }
} 



个人感觉还是这个最好,不过没写换行,可以再加一个if(index%3==0) System.out.println();
0 请登录后投票
   发表时间:2011-04-02  
这个题不错, LZ的思路也很妙啊,MARK
0 请登录后投票
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics