(This is a gathering moment (YY) of the pen test, in the written test did not write out, and later wrote out, I hope that the great God can give a better solution ... PS: Now the interviewer always have the interview to ask the written test programming problem thinking habits, hehe
Topic Brief:
Enter a string and the number of times to print, creating a thread for each character, which is responsible for printing only one character, and multi-threaded looping the string. The effect is as follows:
nonsense not much to say directly on the code:
The public class pen question {//identifies the current character of the output, with the volatile keyword to ensure visibility public static volatile char now;
public static void Main (string[] args) {Scanner Scanner = new Scanner (system.in);
System.out.println ("Please enter the string to be printed:");
String str = scanner.nextline ();
while (Str.length () < 1) {SYSTEM.OUT.PRINTLN ("entered incorrectly, reenter:");
str = Scanner.nextline ();
} char[] chars = Str.tochararray ();
System.out.println ("Please enter the number of cycles printed:");
int temp = Scanner.nextint ();
while (Temp < 1) {SYSTEM.OUT.PRINTLN ("entered incorrectly, reenter:");
temp = Scanner.nextint (); Final int n = temp; Only constants in the method can be accessed in the anonymous inner class for (int j = 0; J < Chars.length; J + +) {Final int t = j;//Anonymous inner class can only access constant Thread th in a method
Read = new Thread (new Runnable () {@Override public void run () {for (int i = 0; i < n; i++) {//the number of times to control the output while (now!= chars[t]) {//Loop wait now to point to the character of the output of the thread} System.out.print (Chars[t]);/output character if (T + 1 < C HARS.LENGTH)//modifies the now value, pointing to the next character of the output now = chars[t + 1];
else now = chars[0];
}
}
});
Thread.Start ();
now = Chars[0]; }
}
Effect Chart:
As to why the anonymous inner class in the method can only access constants. See a blog: http://feiyeguohai.iteye.com/blog/1500108