码迷,mamicode.com
首页 > 编程语言 > 详细

求开4个线程4秒内执行完以下程序;部分代码已标注不能修改(多线程)

时间:2015-03-01 23:33:31      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:

求开4个线程4秒内执行完以下程序;部分代码已标注不能修改

技术分享
 1 public class LogTest {
 2     // 里面的方法不能动
 3     public static void parseLog(String log) {
 4         System.out.println(log + ":" + (System.currentTimeMillis() / 1000));
 5         try {
 6             Thread.sleep(1000);
 7         } catch (Exception e) {
 8             e.printStackTrace();
 9         }
10     }
11 
12     public static void main(String[] args) {
13         System.out.println("begin:" + (System.currentTimeMillis() / 1000));
14         for (int i = 0; i < 16; i++) {// 不能动
15             final String log = "" + (i + 1);// 不能动
16             {
17                 LogTest.parseLog(log);
18             }
19         }
20     }
21 
22 }
View Code
个人解决方案

技术分享
 1 import java.util.Queue;
 2 import java.util.concurrent.ConcurrentLinkedQueue;
 3 
 4 /**
 5  * 要求开4个线程去执行,只要4秒搞定
 6  * 
 7  * @author trfizeng
 8  * 
 9  */
10 public class LogTest {
11     public static Queue<String> logQueue = new ConcurrentLinkedQueue<String>();
12 
13     // 里面的方法不能动
14     public static void parseLog(String log) {
15         System.out.println(log + ":" + (System.currentTimeMillis() / 1000));
16         try {
17             Thread.sleep(1000);
18         } catch (Exception e) {
19             e.printStackTrace();
20         }
21     }
22 
23     public static void main(String[] args) {
24         System.out.println("begin:" + (System.currentTimeMillis() / 1000));
25         for (int i = 0; i < 16; i++) {// 不能动
26             final String log = "" + (i + 1);// 不能动
27             {
28                 // LogTest.parseLog(log);
29                 logQueue.add(log);
30             }
31         }
32         for (int i = 0; i < 4; i++) {
33             new Thread() {
34                 @Override
35                 public void run() {
36                     while (logQueue.size() > 0) {
37                         parseLog(logQueue.poll());
38                     }
39                 }
40             }.start();
41         }
42     }
43 }
View Code
begin:1420042349
1:1420042349
2:1420042349
3:1420042349
4:1420042349
5:1420042350
6:1420042350
7:1420042350
8:1420042350
9:1420042351
11:1420042351
10:1420042351
12:1420042351
13:1420042352
14:1420042352
15:1420042352
16:1420042352

 

求开4个线程4秒内执行完以下程序;部分代码已标注不能修改(多线程)

标签:

原文地址:http://www.cnblogs.com/trfizeng/p/4307692.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!