Chapter VII Java Multithread
7.1 Multi-threaded concept
The meaning of multi-threaded program is that you can divide the program to divide the program into several parallel subsidies. Special is in the network programming, you will have a lot of work to be able to perform concurrently. For example, the network transmission speed is slow, the user input is slower, you can use two independent threads to finish this? Copy; function, without imposing, often display or other functions. Multithreading is compared with single-thread, ordinary Windows adopts a single-threaded program structure, its working principle is that the main program has a message loop, constantly reading the message from the message queue to determine the next step to do, general It is a sub-function, only after the subunies are returned, the main program can receive additional messages. For example, sub-function function is reading a network data, or reading a file, only waiting for the following. Copy; data or document can receive a message. Do you not do this in this sub-function process? However, it is necessary to solve this problem after a lot of time to wait until you have a multi-thread, and multi-threaded use this feature.
7.1.1 Model of Java Thread
Java's design thinking is to build a threaded score in the first major multi-operative system. Many tasks for Java virtual machines relies on threaded scheduling, and all class libraries are multi-threaded settings. In real time, Java supports the platform of Macintosh and MS-DOS? REG; the late late is not supported by these two platforms. Java uses multi-threaded reality, the whole, the whole, is a different step. There is no main message loop in the Java program. If a thread is waiting to read network data, it can run but do not stop the system. The threaded threads used to pass the user is waiting to be used to knock the keyboard or hit the mouse. You can also stop each frame of the moving painting and stop in the system. I. Copy; After the thread is enabled, it can be hung up, and it is not allowed to do it. The hanging thread can be retrofitted. Any time thread can be stopped, and the stopped thread can no longer be reopened. In the Java language, the threads are now thread class, and the thread class encapsulates all the required thread operations. In your heart, you must clearly distinguish between the threads and running the thread, you can use the thread pair to see the control panel for running the thread. There is a lot of functions in the thread pair to control a thread whether it is running, sleep, hangs or stop. The thread class is the only means of controlling thread. One? Copy; After the Java is started, there is a thread to run. You can check which thread is running forward by calling the Thread.currentThread function. One? Copy; you get a thread control handle, you can make a Copy; very interesting thing, that is, the single thread is also. This example makes you know how to operate the front thread. Filename: testthreadclass testthread {public static void main (String args []) {Thread t = Thread.currentThread (); t.setName ( "This Thread is running"); System.out.println ( "The running thread:" T); try {for (INT i = 0; I <5; I ) {system.out.println ("Sleep Time" i); thread.sleep (1000);
} catch (interruptedException e) {system.out.println ("Thread Has Wroge);
}
Executive Fruits: Java Testthread The Running Thread: Thread [this Thread "Sleep Time 0 Sleep Time 1 Sleep Time 2 Sleep Time 3 Sleep Time 4
7.1.2 Starting interface
A thread does not motivate people, and multiple threads have practical meaning. How do we create more threads? We need to create another example of the thread class. When we consider a new instance of the thread class, we must tell it which section of the program should be held in the new thread. You can start a thread on an object of the startup interface. The startup interface is an extraction interface, and the object is a case. Copy; function wants to do it. To realize the interface, a class only needs to have a function called RUN. The following is an example of creating a new thread: FileName: twothread.java
class twothread implements Runnable {twothread () {Thread t1 = Thread.currentThread (); t1.setName ( "The first main thread"); System.out.println ( "The running thread:" t1); Thread t2 = new Thread (this, "the second thread"); System.out.Println ("Creat Another Thread"); T2.Start (); try {system.out.println ("First Thread Will Sleep"); thread.sleep 3000);} catch (interruptedexception e) {system.out.println ("first thread haas wheng");} system.out.println ("first thread exit");} public void run () {TRY {for (int i = 0; i <5; i ) {system.out.println ("Sleep Time for Thread 2:" i); thread.sleep (1000);
} catch (interruptedException e) {system.out.println ("Thread Has Wroge);
System.out.Println ("Second Thread Exit");} public static void main (string args []) {new twothread ();}}
Executive results: Java TwothRead
The running thread: Thread [The first main thread, 5, main] creat another thread first thread will sleep Sleep time for thread 2: 0 Sleep time for thread 2: 1 Sleep time for thread 2: 2 first thread exit Sleep time for thread 2: 3 Sleep Time for Thread 2: 4 SECOND THREAD EXIT
The MAIN thread creates a Thread object with New Thread (this, "The Second Thread"), which is passed through the first parameter to mark the new thread to call the RUN function of the THIS object. Then I call the Start function, which will make the thread to start from the Run function. 7.1.3
Due to multi-threaded to you? COPY; the function of the exquisite line is executed, so it must be mentioned when necessary; a synchronization mechanism. For example, you want two threads to communicate and share a complex data, you need a mechanism to let them mutually mutually understand and are doing. For this purpose, Java has implemented the transformation of the process between the engine with a Monitor. You can see a small box of monitors, which can only accommodate a thread. One? Copy; a thread enters a monitizer, and other threads must wait until the first thread retreats the monitors before entering the monitors. This is the copy; the monitor can be used as aware of the data that is not operated by multiple threads. Multiple multi-threaded systems will be this? Copy; the monographer sets into an object, Java mentioned Copy; a clearer solution. There is no Monitor class; each object defines its own explicit monitor by defining their member function into synchronized, one? Copy; a thread is executed in a synchronized function, other threads cannot call the SYNCHRONIZED function of the same object. .
7.1.4 message
One? Copy; Your program is divided into several logical threads, you must know clearly this? Copy; thread? REG; how to interpret each other. Java mentioned; WAIT and Notify functions to make threads? REG; interchange. A thread can enter the SYNCHRONIZED function of a pair of objects into the state until his thread is explicitly calling it. You can enter the same function in multiple threads and wait for the same call to wake up.
7.2 Java thread example
7.2.1 Explicit Defining Thread
In our single-threaded application, we have not seen the thread because Java can automatically create and control your thread. If you use a browser in Java language, you have seen the Java program that uses multi-threaded Java. You may not pay attention to the two small programs can be run at the same time, or continue to perform in the small steps when you move the scroll. This is not a way to make a multi-thread, but this browser is multi-thread. Multi-threaded Application (or Applet) can use several consequences to complete their work. Multi-thread utilizes a lot of tasks that contain single-independent sub-tasks. Each thread is finished into a child.
However, each thread is completed in a sub-task or it is still in order. A multi-thread process allows each thread to finish them as soon as possible. This feature will have a better real-time input reaction. 7.2.2 Multi-threaded example
The following example creates three single-unique threads, they are divided into self-employed "Hello World":
// define Our Simple Threads.They Will Pause for a Short Time // And the Print Out Their Names and Delay Times Class Testthread Extends Thread {Private String WhoAmi; Private Int Delay DELAY
// u o = = = = = s; delay = s; delay = d;
// Run - The Thread method Similar to main () // when run is finished, the thread dies. // Run is called from the start () method of thread public void run () {// Try to sleep for the specified Time try {sleep (delay);} catch (interruptedException e) {} // now print outade name system.out.println ("Hello World!" WHOAMI " DELAY);}} / ** * Multimtest. A simple multithread thest program * / public class multitest {public static void main (String args []) {TestThread t1, t2, t3; // Create our test threads t1 = new TestThread ( "Thread1", (int) (Math. Readom () * 2000)); T2 = New Testthread ("Thread2", (INT) (Math.Readom () * 2000)); T3 = New Testthread ("Thread3", (INT) (Math.Readom () * 2000));
// Start Each of the threads t1.start (); t2.start (); t3.start ();}
7.2.3 Launch a thread
The main () function is always called when the program is started, because this main () is the place where we create and start threads:
T1 = New Testthread ("thread1", (int));
This line created a new thread. The two parameters of the rear are delivered to the name of the thread and the thread in print information. Reg; pre-delay time. Because I directly control the control thread, we must be able to directly enable it: t1.start ();
7.2.4 Operation thread
If the creation of the thread is normal, T1 should contain an effective line of execution. We control the thread in the thread Run () function. One? Copy; I entered the Run () function, I can do any of the ways in the face. Run () is like main (). One? Copy; Run () is over, this thread is also ending. In this example, we tried to delay a random time (passing the parameter? Copy ;: Sleep () function just simply telling how many milliseconds of the thread rest. If you want to postpone a thread, You should use the SLEEP () function. When thread sleep is Sleep () does not occupy system resources. Other threads continue to work. One? Copy; Delay time, it will print "Hello World" and thread names and delay time.
7.2.5 Pause a thread
We often need to hang a thread without specifying how long it is. For example, if you create a small program containing a moving thread. Also, you make users suspend the movement until they want to resume. You don't want to move the moving thread, but I want it to stop. You can use the suspend () function to control: t1.suspend ();
This function is not allowed to stop the thread forever, you can also use the resume () function to renew the activation thread: t1.resume ();
7.2.6 Stop a thread
The last control of the thread is stopped function STOP (). We use it to stop the thread: t1.stop ();
Note: This does not have this thread, but it stops the thread. And and this thread cannot be reopened with T1.Start (). In our case, we have never going to stop a thread in the explicit. We only make it completely over. Many complex thread examples will need to control each thread. The STOP () function is used in this situation. If you need it, you can test your thread. A thread has been launched and there is no stopped being considered to be activated. T1.isalive () If T1 is activated, this function will return to True.
7.2.7 Animation Example
The next is an Applet example of a package-containing thread:
Import java.awt. *; import java.awt.image.ImageProducer; import java.applet.applet;
Public class activ3 extends applet imports []; mediatracker tracker; int index = 0; Thread Animator
Int MaxWidth, MaxHeight; // Our Off-Screen Components for Double Buffering. Image OFFSCRIMAGE; Graphics OffsCRGC;
// CAN We Paint Yes? Boolean Loaded = false; // Initialize the applet. Set we size and loading the applet public void init () [// set up our image monitor Tracker = new Mediatracker (THIS)
// set the size and width of out @ = 100; MaxHeight = 100;
images = new Image [10]; // Set up the double-buffer and resize our applet try {offScrImage = createImage (maxWidth, maxHeight); offScrGC = offScrImage.getGraphics (); offScrGC.setColor (Color.lightGray); offScrGC. FillRect (0, 0, MaxWidth, Maxheight); Resize (MaxWidth, MaxHeight);} catch (exception e) {E.PrintStackTrace ();}
// load the animation images INTO ARRAY FOR (INT i = 0; I <10; i ) {string imagefile = new string ("images / duke / t" string.valueof (i 1) ". GIF" ); Images [i] = getimage (getDocumentbase (), imagefile: // register this image with the tracker Tracker.AddImage (images [i], i);} Try {// use Tracker To make Sure All The images Are Loaded tracker.waitForll ();} catch (interruptedexception e) {} loaded = true;
// PAINT The Current Frame. Public Void Paint (Graphics G) {if (loading) {g.drawImage (OFFSCRIMAGE, 0, 0, this);}}
// start, setup out () {OFFSCRGC.DRAWIMAGE (IMAGES [INDEX], 0, 0, THIS); Animator = New Thread (this); Animator .start ();
// Run, Do The Animation Work Here. // Grab Animation, Pause, Grab The Next ... public void Run () {// Get The id of the current thread thread me = thread.currentThread ();
// if we animator thread exist, and is the current thread ... while ((AnimaTr! = Null) && (animator == me)) {if (tracker.checkid (index)) {// clear the background and get the next image offScrGC.fillRect (0,0,100,100); offScrGCdrawImage (images [index], 0,0, this); index ; // Loop back to the beginning and keep going if (index> = images.length) {index = 0;}} // delay here SO Animation Looks Normal Try {Animator.Sleep (200);} catch (interruptedException E) {} // Draw the next frame repaint ();}}} 7.3 multi-thread? REG; communication
7.3.1 Growseers and consumers
One important feature of multi-thread is to them? REG; inter-communication can be communicated with each other. You can set the thread to use public objects, each thread can operate an unique operational object. Typical thread interconnection is established on a production person and a consumer model: a thread producing output; another thread is used.
Buffer
Let us create a simple "Alphabet Soup" producer and corresponding consumers.
7.3.2 Great
The beneficient will receive from the Thread class: class producer extends thread {private Soup Soup; private string alphabet = "AbcdefghijklmnopqrStuvwxyz";
Public product (SOUP S) {// Keep Our OWN COPY OF THE Shared Object Soup = S;}
Public void run () {char c; // throw 10 letters INTO THE SOUP FOR (INT i = 0; i <10; i ) {c = alphabet.charat ((int) (math.rabitom () * 26)) Soup.Add (c); // Print A Record of OSR Addition System.out.println ("Added" C "To the Soup."); // Wait A Bit Before We add the next letter try {SLEEP ((int) (math.random () * 1000);} catch (interruptedException e) {}}}}
Note that we have created an example of a SOUP class. The producer uses a SOUP.ADD () function to build a character pool.
7.3.3 consumers
Let us look at the priority of the consumption: class consumer extends thread {private soup soup;
Public Consumer (SOUP S) {// Keep Our Own Copy of The Shared Object Soup = S;}
Public void run () {char c; // Eat 10 letters from the alphabet Soup for (INT i = 0; i <10; i ) {// Grab one letter c = Soup.eat (); //print out the Letter That We Retrieved System.Out.println ("Ate A Letter:" C); // Try {Sleep ((int));} Catch (InterruptedException E) {}}} } Similarly, like producers, we use Soup.eat () to process information. So, what is the SOUP class?
7.3.4 Supervision
SOUP class executes two threads? REG; the function of inter-transmission information. The monitor is an indispensable part of the multi-thread, because it keeps the flow of communication? Let's take a look at the Soup.java file: class soup {private char buffer [] = new char [6]; private int next = 0; // Flags to keep track of out = false; private boolean isempty = True;
Public syschronized char eat () {// we can't eti the isn't anything in buffer while (isempty == true) {TRY {Wait (); // We'll EXIT THIS ISEMPTY TURNS FALSE} catch (InterruptedException E) {}} // Decrement The Count, Since We're Going to Eat One Letter Next -; // DID We Eat True;} = = true;} // WE KNOW The Buffer Can't Be Full, Because We Just Ate Isfull = False; Notify (); // Return The Letter To The Thread That Is Eating Return (Buffer [Next]);}
// method to add letters to the buffer public synchronized void add (char c) {// Wait around until there's room to add another letter while (isFull == true) {try {wait (); // This will exit when isFull Turns false} catch (interruptedException e) {}} // address buffer to the next available spot buffer [Next] = C; // Change the next available spot ; // area we firm; if (Next == 6) {isfull = true;} iSempty = false; notify ();}} SOUP class contains two important features: Data member buffer [] is private, function member Add () and EAT () are public.
Data has privately avoided the data from the producer and consumption. Direct access to the data can be made wrong. For example, if the consumer is an attempt to take the data from the empty buffer, you will get an uncomfortable vision, otherwise, you can only lock the process. The same step visit to avoid the damage of a shared object. When the producer is added to the SOUP, the consumer cannot eat characters, such as such. This symptom is to maintain the important side of the shared parallelism. The Notify () function will call each wait for a thread. Wait until the thread will continue its visit.
7.3.5
Now there is a production person, a consumption and a shared object, how do you realize their interactions? We only need to have a simple control program to start all threads and confirm that every thread is the same shared object with the interview. Here is the code of the control program, SoupTest.java: Class Souptest {public static void main (string args []) {SOUP S = New Soup (); Producter P1 = New Producter (s); Consumer C1 = New Consumer (s) ;
P1.Start (); c1.start ();}}
7.3.6 Monitoring
The production of the producer / consumer model is commonly used to realize the remote monitoring function, which allows the consumption to see the interaction between the production of the baker or the interaction of its part of the same system. For example, in the network, a group of gains can be run on a very multi-work station. The producer can print the document, after printing, a flag will be saved. One (or more? Copy; consumer will save the logo and report the situation during the day at night. In addition, there is an example in a workstation to divide several separate windows. One window is used as user input (producer? Copy;, another window makes the input reaction (consumer? copy ;7.4 thread API list
The next is one? Copy; the method of the commonly used thread class is a list of the method of functionality:
Class Functions: The following is the static function of Thread, you can directly call from the Thread class.
CURRENTTHREAD Returns the Thread pair of running THRead to stop running the front thread, let the system run the next thread Sleep (int N) letting the front thread sleep N milliseconds
Password function: The following function must be called with Thread's instance objects.
The START START function tells the Java operation system to build a line-enclosed environment, then call the Run () function of this thread. Run is a code that will be executed in this thread, and the only function of the runnable interface. When a thread is initialized, call it by the start function, one? Copy; Run function returns, this thread will end. Stop let a thread will immediately terminate, the system will delete the execution environment of this thread is different, SUSPENT pauses the thread, but the system does not destroy the execution environment of the thread, you can use the resume to recover the execution of this thread RESUME recovery The thread enters the running status setPriority (int P) Give thread setting priority getPriority Returns the priority setName (String Name) Give the thread set name GetName
chapter summary:
1. Multi-thread is the important feature of Java language, and the Java language has been encapsulated by Thread classes. 2. Threaded interface named Runnable 3. Runnable 3. REG; Machine system is SYNCHRONIZED keyword 4. Thread? REG; Interconnection Rely on Wait and Notify Messages