This time, we're not using a well-known inner class. The program controls data and executes programs independently.
5 threads rotate the thread pool synchronized wait notify by a given rule
The code is as follows:
1. Independent internal Control data class
Package com.lovo.homework02;/** * Class: Separate internal data to make it easy to modify and control * @author Abe * */public class Printthreadcontext {/** * allowed to execute the key of the thread The initial value is 3 (4th thread) */public static int allowedkey = 3;/** * Method: Convert to the next key that allows the thread to execute * Here is the second thread after the next execution of this thread, out of range, and starting from the first thread */public static void Next () {Printthreadcontext.allowedkey + = 2;if (Printthreadcontext.allowedkey > 4) { Printthreadcontext.allowedkey%= 5;}} /** * Loop run count */public static int number = 100;}
2. Thread's main program
Package com.lovo.homework02;/** * Class: Print thread, print according to Printthreadcontext.next () @author Abe */public class Printthread Implements Runnable {private String str;private int key;private static Object obj = new Object ();p ublic printthread (String STR, int key) {this.str = Str;this.key = key;} @Overridepublic void Run () {for (int i = 0; i < Printthreadcontext.number; i++) {//This still adds a program lock instead of a while loop instead because as the thread grows Only one thread at a time can go into execution//the rest of the infinite loop in the while my machine is instantly jammed ... Not until the execution is complete ... synchronized (obj) {while (Key! = Printthreadcontext.allowedkey) {try {obj.wait ()}; catch ( Interruptedexception e) {e.printstacktrace ();}} System.out.print (str);//Call Method: Next () Printthreadcontext.next (); Obj.notifyall ();}}}
3. Execution procedures
Package Com.lovo.homework02;import Java.util.concurrent.executorservice;import java.util.concurrent.executors;/** * Class: The execution program of the print thread, * @author Abe * */public class Printthreadrunner {public static void main (string[] args) {Executorservice s Ervice = Executors.newfixedthreadpool (5); String[] STRs = {"A", "B", "C", "D", "E"};for (int i = 0; i < 5; i++) {Service.execute (new Printthread (Strs[i], i));} Service.shutdown (); Remember to close the thread pool}}
Java Programming (18.2)-----5 threads rotate the thread pool synchronized wait notify by a given rule