// Test the blocking queue
Packagecom. moshengv. dms. Demo;
Importjava. util. concurrent. BlockingQueue;
Importjava. util. concurrent. Define blockingqueue;
Importjava. util. concurrent. TimeUnit;
PublicclassDemo02 {
// The thread received from the queue
Threadtom;
// The thread sent to the queue
Threadjerry;
BlockingQueuequeue; // blocking queue
ClassTomextendsThread {
Publicvoidrun (){
While (true ){
Try {
Strings = queue. poll (1, TimeUnit. SECONDS); // gets the message. If there is no message, wait for one second. No null
If (s = null ){
System. out. println ("the queue is empty, and you can get it ...");
Continue;
}
System. out. println ("Tom received:" + s );
Thread. sleep (100 );
} Catch (InterruptedExceptione ){
E. printStackTrace ();
}
}
}
}
// Send
ClassjerryextendsThread {
Inti = 0;
Publicvoidrun (){
While (true ){
Strings = "Hi" + I;
Try {
Booleansuccess = queue. offer (s, 5, TimeUnit. SECONDS); // If the queue is full, wait? Seconds. If the plug-in fails, false is returned.
If (success ){
System. out. println ("message added successfully! "+ S );
I ++;
} Else {
System. out. println ("failed to add, the queue is full, retry ..");
Continue;
}
Thread. sleep (2000 );
} Catch (InterruptedExceptione ){
E. printStackTrace ();
}
}
}
}
PublicvoidstartT (){
Queue = neww.blockingqueue (3); // use a linked list to block the queue
Tom = newTom ();
Jerry = newjerry ();
Jerry. start ();
Tom. start ();
}
Publicstaticvoidmain (String [] args ){
NewDemo02 (). startT ();
}
}
// Test the thread pool
Packagecom. moshengv. dms. Demo;
Importjava. util. concurrent. Executor;
Importjava. util. concurrent. Executors;
Publicclassdemo01 {
Publicstaticvoidmain (String [] args ){
// Executor is an abstract class Executor, using the factory Method
Executorexecutor = Executors. newFixedThreadPool (3); // obtain the thread pool object from the factory
Executor.exe cute (newDog ("golden"); // The first thread
Executor.exe cute (newDog ("Chinese Rural dog"); // The second thread
Executor.exe cute (newDog ("husky"); // The third thread
Executor.exe cute (newDog ("Teddy"); // The fourth thread. Because the thread pool size is 3, the execution starts when three people exit.
Executor.exe cute (newDog ("Tibetan mastiff"); // The Fifth thread, waiting for the previous thread to run
}
}
// Create a thread to implement the run Method
ClassDogimplementsRunnable {
Stringname;
PublicDog (Stringname ){
This. name = name;
}
Publicvoidrun (){
For (inti = 0; I <3; I ++ ){
System. out. println (name + "running" + I );
Try {
Thread. sleep (1000 );
} Catch (effectione ){
}
}
System. out. println (name + "over ");
}
}