Thread foundation of Java 101

zhaozj2021-02-08  525

Author: Al Saganich

The thread is a part of the Java language, and is one of the most powerful features of Java. What exactly is a thread, why do I develop thread-based applications? In this article, we will understand the usage of threads and some techniques using threads. Before we start talking about threads, you should first understand the background knowledge and analyze the working principle of threads.

When the programmer develops an application, these applications can only complete one more. The application is executed from the main program until the end of the run, is the language like Fortran / COBOL / BASIC.

Over time, the computer has developed to run more than one application in the same time period, but the application is still serial, that is, from the beginning to the end, the next instruction is then executed . To recently, the program has developed to run in a number of threads when executed. Java has the ability to run multiple threads, can do a few operations in the same time period, which means that a given operation does not have to wait until the end of another operation, it can begin. And you can specify a higher level of priority to a certain action.

Many programming languages, including ADA, MODULA-2, and C / C , have been able to support threads. Compared with these languages, Java features support from the thread from the bottom. In addition, the standard Java class is reusable, allowing the same method to be called in a given application, and threads do not interfere with each other. These features of Java laid the foundation for the design of multi-threaded applications.

What is thread?

What is the thread? As shown in Figure A, a thread is a sequence of a given instruction (the code you written), a stack (variable defined in a given method), and some shared data (class one-level variable) . Threads can also access static data from the global class.

Stack and some shared data

Each thread has its own stack and program counters (PC). You can assume the program counter (PC) as the instruction for tracking the thread being executed, and the stack is used to track the context of the thread, the context is the value of the current local variable when the thread is executed to somewhere. Although you can write a subroutine that transmits data between threads, in normal conditions, a thread cannot access the stack variable of another thread.

A thread must be one of the following four possible states, these four states:

Initial state: A thread calls the new method and is in the state before calling the start method. In the initial state, you can use the Start and STOP methods. Runnable: Once the thread calls the start method, the thread is turned to the RunNable status. Note that if the thread is in the Runnable status, it may not run, because there is also priority and scheduling issues. Blocking / NonRunnable: The thread is in the block / NonRunNable state, which is caused by two possibilities: either suspension due to hangs, or because of some reasons, including the completion of waiting for the IO request. Exit: The thread goes to an exit state, which has two possibilities, or the RUN method is completed, or the STOP method is called. The last concept is the priority of the thread, and the thread can set the priority, and the high priority thread can be scheduled before the low priority thread is completed. An application can set the priority size of the thread by using method setPriority (int) in the thread.

We have already described the basic knowledge of threads, now we can take a look at the two mechanisms that Java provide us to develop thread-based applications: thread class and Runnable interface. Derived thread class

The simplest method of writing a thread-based code is to derive the Java.lang.Thread class. The thread class is a member of the java.lang package, where the thread class can be called by all Java applications by default. In order to use the thread class, we need to understand the five methods defined in the Java.lang.Thread class:

Run (): This method is used for thread execution. You need to overload this method so that threads do specific work. START (): This method allows the thread to start Run (). STOP (): This method is opposite to the role of the Start method, stop the running of the thread. Suspend (): This method is different from the stop method. It does not terminate unfinished threads, which only hangs the thread, and will be recovered later. Resume (): This method restarts the already hanging thread.

Run the program in List A, see List B

List A: Extended thread class

Class testthreads {

Public static void main (string args []) {

Class mythread extends thread {

String which;

Mythread (string which) {

THIS.WHICH = Which;

}

Public void run () {

INT ITERATIONS = (INT) (Math.random () * 100)% 15;

INT SLEPINTERVAL = (INT) (Math.random () * 1000);

System.out.println (Which "Running for" Items "Itemions");

System.out.println (Which "Sleeping for" Sleepinterval "MS Between LOOPS");

For (int i = 0;

System.out.println (Which " i);

Try {

Thread.sleep (SleepInterval);

} catch (interruptedexception e) {}

}

}

}

Mythread a = new mythread ("Thread A");

Mythread B = New Mythread ("Thread B");

Mythread C = New Mythread ("Thread C");

a.Start ();

B.Start ();

C.START ();

}

}

Listb: Output of List A

Thread A running for 16 iterations Thread C running for 15 iterations Thread B running for 14 iterations Thread A sleeping for 305ms between loops Thread C sleeping for 836ms between loops Thread B sleeping for 195ms between loops Thread A 0 Thread C 0 Thread B 0.. Thread C 13 Thread B 13 Thread A 14 Thread C 14 Thread A 15List A Demonstrate how to generate a new class from the existing Thread class. The newly created class is overloaded with the RUN method. Interestingly, achieving the RUN method does not have to be strict, because the Thread class provides a default RUN method, although it is not particularly useful.

In some cases, we cannot simply change the parent class of the specified object. We still need to use a thread. At this time, we need to use the Runnable interface.

Use Runnable interface

The second method of developing thread applications is implemented by runnable interface. In a lot of occasions, you can't redefine the parents of the class, or you can't define the derived thread class, maybe your class's level requires your parent class as a specific class. In these cases, multi-threading can be implemented through the runnable interface.

Tip: The interface is a complex technology, and it is necessary to completely understand its usage. Interested readers can read my previous article "Explanation", published in May 1998 Visual J Developer's Journal Magazine.

List C is a simple animation applet, which is an example of using the runnable interface. This example can be placed on the web, it needs to be derived from the Applet class. The purpose of this applet is to color the image to display an animation. Because the animation takes up a lot of processor time, we don't plan to block the operation of other processes when the image is colored. For example, if you intend to stop the animation, we don't want to wait until it runs, then call the STOP method. In other words, we can make the small program thread.

List C: Animation applet

Import java.applet. *;

Import java.awt. *;

Public Class Tstrunnable Extends Applet

Implements runnable {

Private thread m_thread = NULL;

Private image m_images [];

Private image m_currentimage = NULL;

Private int m_nimgwidth = 0;

Private int m_nimgheight = 0;

Private Boolean M_FallLoaded = Alse;

PRIVATE FINAL INT NUM_IMAGES = 18;

Public tstrunnable () {}

Private Void DisplayImage (graphics g) {

IF (NULL! = m_currentimage)

g.drawimage (M_CurrentImage, (getSize (). width - m_nimgwidth/2,

(GetSize (). HEIGHT - M_NIMGHEIGHT / 2, NULL);

}

Public void paint (graphics g) {

IF (NULL! = m_currentimage) {

Rectangle r = g.getClipbounds (); g.clearRect (R.X, R.Y, R.Width, R.Height);

DisplayImage (g);

}

Else

g.drawstring ("Loading Images ...", 10, 20);

}

// The applets start method is caled when the page is first shown.

Public void start () {

IF (m_thread == null) {

m_thread = new thread (this);

m_thread.start ();

}

}

// the applets stop method is caled. The page is hidden.

Public void stop () {

IF (m_thread! = null) {

m_thread.stop ();

m_thread = NULL;

}

}

// the run method is buy by the thread

// Object We create in this start method.

Public void run () {

INT IWHICHIMAGE = 0;

Graphics m_graphics = getGraphics ();

Repaint ();

M_Graphics = getGraphics ();

M_Images = newimage [num_images];

Mediatracker Tracker = New Mediatracker (this);

String strimage;

For (INT i = 1; i <= num, i ) {

M_Images [i-1] = GetImage (getCodeBase (),

"img" new integer (i) .tostring () ".gif");

Tracker.AddImage (m_images [i-1], 0);

}

Try {

Tracker.waitForl ();

m_fallloaded =! tracker.iserroorany ();

} catch (interruptedexception e) {}

IF (! m_fallloaded) {

STOP ();

M_Graphics.drawstring ("Error Loading Images!", 10, 40);

Return;

}

// Assuming All images Are The Same

// Width and Height.

// ------------------------------------

m_nimgwidth = m_Images [0] .Getwidth (this);

M_nImgheight = m_Images [0] .getheight (this);

Repaint ();

While (true) {

Try {

// Draw next image in animation.

M_CurrentImage = m_currentimage = m_Images [ilhichimage];

DisplayImage (M_Graphics);

IWHICHIMAGE = (IWHICHIMAGE 1)% NUM_IMAGES;

Thread.sleep (50);

} catch (interruptedexception e) {

STOP ();

}

}

}

}

We use the runnable interface to implement threads without the way of creating a thread class. Using the runnable interface, we need to implement the RUN method. We also need to create an instance of the Thread object, which is ultimately used to call the RUN method. In the START method in the applet, we generate a Thread object by using the Thread constructing method, and its parameters are any class that implements the runnable interface. The Thread object launches the RUN method that has been defined, and the RUN method is used for animation display. Of course, a class is generated from the thread class and create an instance in the Applet Delivery class, and we can complete the same thing. This example is used to demonstrate the usage of the Runnable interface. Before we read, there were several questions to answer. You may ask, the browser calls the START and STOP methods of the Java applet? How is the RUN method called? The situation is that when the browser starts an internal thread, start the applet's operation. When the web is displayed, the start method of the applet is launched. The Start method creates a thread object and transmits the Applet itself to the thread to implement the RUN method.

At this point, two threads are running: the initial thread that is started by the browser, and the thread of the animation. Quickly view the Start method of the applet, you can know that it creates a thread and starts it. Similarly, when the web is hidden, the APPLET's STOP method calls the thread's STOP method.

Note: START / STOP subroutines in Applets and Threads

There are START and STOP methods in both classes of Applet and Thread, but their features are different. Once the Applet is displayed, call the Applet's Start method. Once Applet hide, the Applet's STOP method is called. Instead, the start method of the thread will call the RUN method, and the thread's STOP method will stop the thread being executed.

Image principle of the animation program

Since we have seen how animation started. Now look at its mechanism. First, we write a small program by defining the Runnable interface. Once the interface is defined, we will show that we will implement the RUN method.

Public Class Tstrunnable

Extends Applet Implements Runnable..

Then we write the RUN method, which will be called by the movie thread.

Public void run () {

.

}

We also need a thread object that will manage our animation threads, such as:

Private thread m_thread = NULL;

Once these preparations are made, when the applet is first displayed, an instance of the thread object is created, and the THIS object is used as the parameter of the construction method, and then the animation can be started:

Public void start () {

IF (m_thread == null) {

m_thread = new thread (this);

m_thread.start ();

}

}

The last step is written as follows: Once the applet is hidden, stop the animation, and the Applet's STOP method is as follows:

Public void stop () {

IF (m_thread! = null) {

m_thread.stop ();

m_thread = NULL;

}

}

in conclusion

转载请注明原文地址:https://www.9cbs.com/read-446.html

New Post(0)