20-空中网挑选实习生的面试题(1)
题目:
package cn.itcast.demo.thread;
public class Test {
public static void main(String[] args) {
System.out.println("begin:" + System.currentTimeMillis()/1000);
for (int i=0; i<16; i++) { // 这行代码不能动
final String log = "" + (i+1); // 这行代码不能动
{
Test.parseLog(log);
}
}
}
public static void parseLog(String log) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(log + ":" + System.currentTimeMillis()/1000);
}
}
1:1503370929 2:1503370930 3:1503370931 4:1503370932 5:1503370933 6:1503370934
答案:
package cn.itcast.demo.thread; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; public class Test { public static void main(String[] args) { // 创建有界堵塞队列,放16个数据 final BlockingQueue<String> queue = new ArrayBlockingQueue<String>(16); // 创建四个线程去取数据 for (int i=0; i<4; i++) { new Thread(new Runnable() { @Override public void run() { try { while (true) { String log = queue.take(); Test.parseLog(log); } } catch (InterruptedException e) { e.printStackTrace(); } } }).start(); } System.out.println("begin:" + System.currentTimeMillis()/1000); for (int i=0; i<16; i++) { // 这行代码不能动 final String log = "" + (i+1); // 这行代码不能动 { //Test.parseLog(log); // 放16个数据 try { queue.put(log); } catch (InterruptedException e) { e.printStackTrace(); } } } } public static void parseLog(String log) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(log + ":" + System.currentTimeMillis()/1000); } }
begin:1503372052 4:1503372053 3:1503372053 1:1503372053 2:1503372053 5:1503372054 6:1503372054 7:1503372054 8:1503372054 9:1503372055 10:1503372055 11:1503372055 12:1503372055 14:1503372056 13:1503372056 15:1503372056 16:1503372056