JAVA programming (18.1) ----- 1 multi-thread rotation printing Thread Scheduling thread pool synchronized wait notify internal class, synchronizednotify
1. Two threads print A, one print B, and the other two threads print data in turn.
Multi-threaded Junior Application Thread Scheduling thread pool (N threads are created in advance, and the required program is called directly. After the execution is completed, the thread pool is returned. The typical internal class uses the space for the synchronized wait y.
Package com. lovo; import java. util. concurrent. executorService; import java. util. concurrent. executors;/*** class: Test wait notify usage * print AB * @ author Abe */public class TestNotify {public static void main (String [] args) {// the size of the thread pool to be created is 2 ExecutorService service = Executors. newFixedThreadPool (2); // initialize two threads and startString [] str = {"A", "B"}; for (int I = 0; I <2; I ++) Configure service.exe cute (new MyPrinter (str [I], 1 00);} // close the thread pool service after all threads are finished. shutdown () ;}/ *** internal class: the thread running content interface Runable and override the run method ** @ author Abe **/class MyPrinter implements Runnable {private String str; private int number; public static boolean check = false; private static Object obj = new Object (); public MyPrinter (String str, int number) {this. str = str; this. number = number;} public String getStr () {return str;} public void print () {System. out. pri Nt (str);}/*** rewrite method: thread running method A 0 lock Program 2 wake up Wait pool 3 A print 4 enter wait pool, and unlock the Program * B 1 program is locked out of the program waiting (not into the waiting pool) 5 program to unlock, enter and lock the Program * 6 first wake up the waiting pool 7 then A is awakened, but the program is locked, wait out of the program * 8 B print 9 into the wait pool, and unlock the Program * A to repeat the loop from the B-5... * // @ Overridepublic void run () {// After the thread whose name is A is printed for the first time, check changes to true. All threads can enter this sentence and it becomes invalid while (check = false &&! This. str. equals ("A") {}for (int I = 0; I <number; I ++) {synchronized (obj) {obj. running y (); print (); check = true; try {// ∞ each loops to its own last time and no longer enters the waiting pool. The thread terminates if (I <number-1) {obj. wait () ;}} catch (InterruptedException e) {e. printStackTrace ();}}}}}