1. Java and Its APIs can both use concurrency. You can specify that the program contains different execution threads. Each thread has its own method call stack and program counter, so that threads can concurrently execute with other threads to share resources within the program scope, for example, shared memory is called multithreading, which is not available in the core C and C ++ languages, even though it affects Java design.
2. Thread Lifecycle
The life cycle of a new thread starts from the new state. Before a program starts a thread, the thread remains in the "new" state. After the program starts a thread, the thread enters the "runable" state. A thread in the "runable" status is considered to be executing its task.
Before the program starts the thread, the thread remains in the "Waiting" state. Only when the other thread notifies the waiting thread to continue the execution, this thread will be restored from the "Waiting" status to the "runable" status.
A thread in the "runable" status can enter the "timed wait" status, waiting for a specified period of time. When the time reaches or a thread is waiting for an event, the thread returns the "runable" status. Even if the processor can be used, threads in the "timed wait" and "Waiting" statuses cannot use it. When a thread in the "runable" status is waiting for another thread to execute the task, if it provides an optional waiting period, the thread enters the "timed waiting" status. When another thread notifies the thread, or when the scheduled time period arrives (whichever is satisfied first), the thread will return to the "runable" status .. Another way for a thread to enter the "timed wait" state is to sleep a thread in the "runable" state. A sleep thread will maintain a specified period of time (called a sleep period) in the "timed wait" state. After this period, it will return to the "runable" state. When the thread has no job to execute, it will immediately sleep .; Example
When a thread tries to execute a task and the task cannot be completed immediately, the thread changes from the "runable" status to the "blocking" status .; Example. Even if a processor is available, a thread in the "blocking" status cannot use it.
When the thread successfully completes the task or terminates (due to an error), the "runable" thread enters the "terminated" state (sometimes called "stuck ).
At the operating system level, Java's "runnable" State usually contains two independent states. When the thread first switches from the "new" status to the "runable" status, the thread is in the "ready" status. When the operating system gives the thread to the processor, the thread enters the "running" state (that is, the execution starts) from the "ready" state, which is also called the "scheduling thread ". In most operating systems, each thread is assigned a short processor time (time slice) to execute the task. When the time slice arrives, the thread returns to the "ready" state, and the operating system gives another thread to the processor.
3. thread priority and Thread Scheduling
Java thread priority ranges from min_priority (constant 1) to max_priority (constant 10). The default value is norm_priority (constant 5)
4. Create and execute a thread
Create thread recommendation to implement the runnable interface
(1) runnable and thread classes
// Fig. 4.1: PrintTask.java// PrintTask class sleeps for a random time from 0 to 5 secondsimport java.util.Random; public class PrintTask implements Runnable { private final int sleepTime; // random sleep time for thread private final String taskName; // name of task private final static Random generator = new Random(); public PrintTask( String name ) { taskName = name; // set task name // pick random sleep time between 0 and 5 seconds sleepTime = generator.nextInt( 5000 ); // milliseconds } // end PrintTask constructor // method run contains the code that a thread will execute public void run() { try // put thread to sleep for sleepTime amount of time { System.out.printf( "%s going to sleep for %d milliseconds.\n", taskName, sleepTime ); Thread.sleep( sleepTime ); // put thread to sleep } // end try catch ( InterruptedException exception ) { System.out.printf( "%s %s\n", taskName, "terminated prematurely due to interruption" ); } // end catch // print task name System.out.printf( "%s done sleeping\n", taskName ); } // end method run} // end class PrintTask
// Fig. 4.2 threadcreator. java // creating and starting three threads to execute runnables. import Java. lang. thread; public class threadcreator {public static void main (string [] ARGs) {system. out. println ("creating Threads"); // create each thread with a new targeted runnable thread thread1 = new thread (New printtask ("task1 ")); thread thread2 = new thread (New printtask ("task2"); thread thread3 = new thread (New printtask ("task3"); system. out. println ("Threads created, Starting tasks. "); // start threads and place in runnable state thread1.start (); // invokes task1 implements run method thread2.start (); // invokes task2 implements run method thread3.start (); // invokes task3 submit run method system. out. println ("tasks started, main ends. \ n ");} // end main} // end class runnabletester
(2) thread management and executor framework
. 5. It is the creation thread for display, but the executor interface is recommended to manage the execution of runnable objects. The executor object creates and manages the threads of a set of runnable objects. This set of threads is used as the thread pool ). the advantage is that the executor object can reuse existing threads to reduce the overhead of creating new threads for each task and improve performance.
The executor interface only declares a method named execute and receives a real runnable parameter. Executor will assign each runnable object passed to his execute method to a thread pool that can be used. If there is no available thread, the executor will create a new thread, or wait for a thread to become available, and assign this thread to the runnable object passed to the execute method.
The executorservice interface extends the executor interface.
// Fig. 4.3: TaskExecutor.java// Using an ExecutorService to execute Runnables.import java.util.concurrent.Executors;import java.util.concurrent.ExecutorService;public class TaskExecutor{ public static void main( String[] args ) { // create and name each runnable PrintTask task1 = new PrintTask( "task1" ); PrintTask task2 = new PrintTask( "task2" ); PrintTask task3 = new PrintTask( "task3" ); System.out.println( "Starting Executor" ); // create ExecutorService to manage threads ExecutorService threadExecutor = Executors.newCachedThreadPool(); // start threads and place in runnable state threadExecutor.execute( task1 ); // start task1 threadExecutor.execute( task2 ); // start task2 threadExecutor.execute( task3 ); // start task3 // shut down worker threads when their tasks complete threadExecutor.shutdown(); System.out.println( "Tasks started, main ends.\n" ); } // end main} // end class TaskExecutor
5. Thread Synchronization
(1) thread synchronization coordinates multiple concurrent threads to access Shared data. This method synchronizes multiple threads to ensure that every thread accessing the shared object can synchronously exclude all other threads. This is called "mutex ".
Another method is to use the Java built-in monitor ). Each object has a monitor and monitoring lock (or built-in lock ). The monitor ensures that the monitoring lock is held by the maximum possible unique thread at any time.
(2) synchronous data sharing: Perform atomic operations.
// Adds integers to an array shared with other Runnablesimport java.lang.Runnable; public class ArrayWriter implements Runnable{ private final SimpleArray sharedSimpleArray; private final int startValue; public ArrayWriter( int value, SimpleArray array ) { startValue = value; sharedSimpleArray= array; } // end constructor public void run() { for ( int i = startValue; i < startValue + 3; i++ ) { sharedSimpleArray.add( i ); // add an element to the shared array } // end for } // end method run} // end class ArrayWrite
// Fig 5.2: SharedArrayTest.java// Executes two Runnables to add elements to a shared SimpleArray.import java.util.concurrent.Executors;import java.util.concurrent.ExecutorService;import java.util.concurrent.TimeUnit; public class SharedArrayTest{ public static void main( String[] arg ) { // construct the shared object SimpleArray sharedSimpleArray = new SimpleArray( 6 ); // create two tasks to write to the shared SimpleArray ArrayWriter writer1 = new ArrayWriter( 1, sharedSimpleArray ); ArrayWriter writer2 = new ArrayWriter( 11, sharedSimpleArray ); // execute the tasks with an ExecutorService ExecutorService executor = Executors.newCachedThreadPool(); executor.execute( writer1 ); executor.execute( writer2 ); executor.shutdown(); try { // wait 1 minute for both writers to finish executing boolean tasksEnded = executor.awaitTermination( 1, TimeUnit.MINUTES ); if ( tasksEnded ) System.out.println( sharedSimpleArray ); // print contents else System.out.println( "Timed out while waiting for tasks to finish." ); } // end try catch ( InterruptedException ex ) { System.out.println( "Interrupted while wait for tasks to finish." ); } // end catch } // end main} // end class SharedArrayTest
// Fig.5.3 : SimpleArray.java// Class that manages an integer array to be shared by multiple // threads with synchronization.import java.util.Random; public class SimpleArray{ private final int array[]; // the shared integer array private int writeIndex = 0; // index of next element to be written private final static Random generator = new Random(); // construct a SimpleArray of a given size public SimpleArray( int size ) { array = new int[ size ]; } // end constructor // add a value to the shared array public synchronized void add( int value ) { int position = writeIndex; // store the write index try { // put thread to sleep for 0-499 milliseconds Thread.sleep( generator.nextInt( 500 ) ); } // end try catch ( InterruptedException ex ) { ex.printStackTrace(); } // end catch // put value in the appropriate element array[ position ] = value; System.out.printf( "%s wrote %2d to element %d.\n", Thread.currentThread().getName(), value, position ); ++writeIndex; // increment index of element to be written next System.out.printf( "Next write index: %d\n", writeIndex ); } // end method add // used for outputting the contents of the shared integer array public String toString() { String arrayString = "\nContents of SimpleArray:\n"; for ( int i = 0; i < array.length; i++ ) arrayString += array[ i ] + " "; return arrayString; } // end method toString} // end class SimpleArray