用与一个字符串长度相等的数量的线程,顺序输出N行相同的字符串

举例,输出N行的字符串"ABC",就要用3个线程,每个线程分别负责输出一个字符,输出结果应该为N行的"ABC"

我的思路是:
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));
		}
	}
}


这个是属于空间换时间的,不需要同步,速度应该会比加锁的要快吧?


另外一种方法:
public class Tester {
	public static void main(String[] arg) {
		String str = "abc";
		Integer[] locker = new Integer[1];
		locker[0] = 0;
		for (int i = 0; i < str.length(); i++) {
			new Thread(new printStr(locker, str, 10)).start();
		}
	}
}

class printStr implements Runnable {
	Integer[] locker = null;
	String str = null;
	int COUNT;

	public printStr(Integer[] locker, String str, int cOUNT) {
		super();
		this.locker = locker;
		this.str = str;
		COUNT = cOUNT;
	}

	@Override
	public void run() {
		synchronized (locker) {
			while (locker[0] < str.length() * COUNT) {
				System.out.print(str.charAt(locker[0]++ % str.length()));
				if (locker[0] % str.length() == 0)
					System.out.println();
				try {
					locker.notifyAll();
					locker.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			locker.notifyAll();
		}
	}
}










你可能感兴趣的:(thread)