1. Two threads one print a one print B another two threads take turns printing work
Multithreaded primary application thread dispatching thread pool (pre-established n threads, required programs are called directly, returned to the thread pool after execution, typical space change time synchronized wait notify internal class use
Package Com.lovo;import Java.util.concurrent.executorservice;import java.util.concurrent.executors;/** * class: Test wait Notify usage * Sequential Print AB * @author Abe */public class Testnotify {public static void main (string[] args) {//create thread pool size 2ExecutorS Ervice service = Executors.newfixedthreadpool (2);//Initialize two threads separately and startstring[] str = {"A", "B"};for (int i = 0; i < 2; i++) {Service.execute (new Myprinter (Str[i], 100));} Close thread pool Service.shutdown () After all threads have finished;}} /** * Internal class: Thread runs the content interface Runable and overrides the Run method * * @author Abe * */class Myprinter implements Runnable {private String str;private in T number;public static Boolean check = False;private static Object obj = new Object ();p ublic myprinter (String str, int num ber) {this.str = Str;this.number = number;} Public String Getstr () {return str;} public void print () {System.out.print (str);} /** * Override method: Thread Run method a 0 lockout program 2 first wake up wait Pool 3 A print 4 Enter wait pool and unlock program * B 1 program is locked out of program waiting (not into waiting pool) 5 program unlocked, enter and lock program * 6 Wake Up wait Pool 7 at this time A is awakened, but the program is Lock, wait outside the program * 8 B print 9 into the waiting pool, and unlock program * A repeats the loop starting from B-5 ... */@OverridepuBlic void Run () {//The first time a thread that can only be printed as a comes in and then check becomes true all threads can come in this sentence fails while (check = = False &&!this.str.equals ("a")) {}for (int i = 0; i < number; i++) {synchronized (obj) {obj.notify ();p rint (); check = true;try {//∞ Each loop to its last time no longer enters the wait pool, the thread terminates if (I < number-1) {obj.wait ( );}} catch (Interruptedexception e) {e.printstacktrace ();}}}}
Java Programming (18.1)-----1 multi-thread rotation print thread scheduling threads pool synchronized wait notify inner class