Original post see: http://www.iteye.com/topic/1117703
Problem Description:
A classic interview question about threading, requiring three threads to print 1,2,3,4,5 in order .... 71,72,73,74, 75.
Thread 1 Prints the 1,2,3,4,5 first, then the thread 2 prints the 6,7,8,9,10, then the thread 3 prints 11,12,13,14,15. Then the thread 1 prints 16,17,18,19,20 ... and so on until thread 3 prints to 75.
Directly on the code:
Java code package concurrent.test; /** * Requirements Create three threads, output 1-75, * first thread output 1-5, second output 6-10, third output 11-15 * then first thread output 16-20 ... Just go through the loop until you print out 75 numbers * @author qiaoxueshi * */ public class print1to75 { static class printer implements Runnable{ static int num = 1; //Start Digital static final int END = 75; int id; Public printer (int id) { this.id = id; } @ override public void run () { synchronized (Printer.class) { while (num <= end) { if (Num / 5 % 3 == id { //If it belongs to its own number, print out five system.out.print (id + ":"); &NBsp; for (int i = 0; i < 5; i++) { system.out.print (num++ + ", ") ); } System.out.println (); &Nbsp; printer.class.notifyall (); /Discard CPU usage, wake up the print threads waiting on the Print.class queue }else{ try { printer.class.wait () ;//If not own number, hangs the current thread on the Printer.class object's waiting queue (also abandons the CPU right), waits for the wake-up } catch (interruptedexception e) { SYSTEM.OUT.PRINTLN ("id" + "interrupted"); } } } } } } public static void main (String[] args) { //below can not press 0, 1,2 in the order, and in the middle of 22 casuallySleep (), will print correctly new thread ( new Printer (0)). Start (); new thread ( new printer (1)). Start (); new thread ( New printer (2)). Start (); } }
The comments are very clear, there are questions to welcome discussion.
Results (run n times, the results are consistent, please check):
Java code 0:1, 2, 3, 4, 5, 1:6, 7, 8, 9, 10, 2:11, 12, 13, 14, 15, 0:16, 17, 18, 19, 20, 1:21, 22, 23, 24, 25, 2:26, 27, 28, 29, 30,