Open 4 threads to execute the following programs within 4 seconds; part of the code has been marked cannot be modified
1 Public classLogtest {2 //the method inside can't move.3 Public Static voidParselog (String log) {4SYSTEM.OUT.PRINTLN (log + ":" + (System.currenttimemillis ()/1000));5 Try {6Thread.Sleep (1000);7}Catch(Exception e) {8 e.printstacktrace ();9 }Ten } One A Public Static voidMain (string[] args) { -SYSTEM.OUT.PRINTLN ("Begin:" + (System.currenttimemillis ()/1000)); - for(inti = 0; I < 16; i++) {//can't move . the FinalString log = "" + (i + 1);//can't move . - { - logtest.parselog (log); - } + } - } + A}
View Code
Personal Solutions
1 ImportJava.util.Queue;2 ImportJava.util.concurrent.ConcurrentLinkedQueue;3 4 /**5 * requires 4 threads to execute, just 4 seconds to get it done.6 * 7 * @authorTrfizeng8 * 9 */Ten Public classLogtest { One Public StaticQueue<string> Logqueue =NewConcurrentlinkedqueue<string>(); A - //the method inside can't move. - Public Static voidParselog (String log) { theSYSTEM.OUT.PRINTLN (log + ":" + (System.currenttimemillis ()/1000)); - Try { -Thread.Sleep (1000); -}Catch(Exception e) { + e.printstacktrace (); - } + } A at Public Static voidMain (string[] args) { -SYSTEM.OUT.PRINTLN ("Begin:" + (System.currenttimemillis ()/1000)); - for(inti = 0; I < 16; i++) {//can't move . - FinalString log = "" + (i + 1);//can't move . - { - //logtest.parselog (log); in logqueue.add (log); - } to } + for(inti = 0; I < 4; i++) { - NewThread () { the @Override * Public voidrun () { $ while(Logqueue.size () > 0) {Panax Notoginseng Parselog (Logqueue.poll ()); - } the } + }.start (); A } the } +}
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
Open 4 threads 4 seconds to execute the following programs; part of the code has been annotated cannot be modified (multithreaded)