1. 程式人生 > >每隔一秒列印一次日誌,共16秒列印完,加4個執行緒修改程式,使之4秒列印完

每隔一秒列印一次日誌,共16秒列印完,加4個執行緒修改程式,使之4秒列印完

原來的程式:

package test1;

public class ThreadTest2 {
	public static void main(String[] args) {
		try {
			for (int i = 0; i < 16; i++) { // 此行程式碼不能動
				final String log = "" + (i + 1);// 此行程式碼不能動
				parseLog(log);
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	public static void parseLog(String log) throws InterruptedException {
		System.out.println(log + ":" + System.currentTimeMillis() / 1000);
		Thread.sleep(1000);
	}
}

用4個執行緒和一個阻塞佇列,修改此程式

package test1;

import java.util.concurrent.ArrayBlockingQueue;

public class ThreadTest1 {
	public static void main(String[] args) {
		
		final ArrayBlockingQueue<String> q = new ArrayBlockingQueue<String>(16);
		System.out.println("begin:" + System.currentTimeMillis() / 1000);
		
		for (int i = 0; i < 4; i++) {
			new Thread(new Runnable() {
				@Override
				public void run() {
					while (true) {
						try {
							String log = q.take();
							parseLog(log);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
			}).start();
		}
		
		for (int i = 0; i < 16; i++) { // 此行程式碼不能動
			final String log = "" + (i + 1);// 此行程式碼不能動
			try {
				q.put(log);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	public static void parseLog(String log) throws InterruptedException {
		System.out.println(log + ":" + System.currentTimeMillis() / 1000);
		Thread.sleep(1000);
	}
}