Deep Analysis of Java thread knowledge

Source: Internet
Author: User
In general, we call a program that is being executed in a computer a process instead of a program ). The so-called "Thread" is the control flow of a single sequence in the "process. Emerging Operating System, Such as Mac, WindowsNT, Windows 95, and so on. Most of them adopt the multi-thread concept and regard the thread as the basic execution unit. Thread is also a very important part of Java.

Even the simplest applet is completed by multiple threads. In Java, the painting () and update () Methods of any Applet are called by AWT (Abstract Window Toolkit) plotting and event processing threads, the main milestone methods of Applet-Init (), start (), stop () and destory ()-are called by the application that executes the applet.

The concept of a single thread is nothing new. What is really interesting is that multiple threads are used in a program to complete different tasks at the same time. In some cases, lightweig HT process is used to replace threads. The similarity between threads and real processes lies in that they are a single sequential control flow. However, a thread is considered lightweight because it runs in the context of the entire program and can use the resources and environment shared by the entire program.

As a single sequential control flow, the threads in the running program must have some resources as necessary overhead. For example, the code that must have an execution stack and a program counter to execute in the thread only plays a role in its context. Therefore, in some places, "execution context" is used to replace "Thread ".

  Thread attributes

To correctly and effectively use a thread, you must understand all aspects of the thread and the Java real-time system. You must know how to provide the thread body, the thread life cycle, how the Real-Time System Schedules threads, thread groups, and what is a ghost thread (Demo nthread ).

(1) thread body

All operations occur in the thread body. In Java, the thread body is the run () method inherited from the Thread class, or the run () method in the class that implements the runnable interface. After a thread is generated and initialized, the real-time system calls its run () method. The code implementation in the run () method produces the thread behavior, which is the main part of the thread.

(2) thread status

The figure below shows the state of a thread at any time in its life cycle and the method that causes the state change. This is not a complete finite state diagram, but it basically summarizes the more interesting and common aspects of the thread. The following describes how to use the thread lifecycle as the data.

● New thread)

A new thread is generated when a thread object is generated. When a thread is in the "New thread" state, it is only an empty thread object and has not been allocated to system resources. Therefore, you can only start or stop it. AnyOthersOperation will cause an exception.

● Runnable)

The START () method generates the resources required by the running thread, schedules the thread to execute, and calls the run () method of the thread. The thread is in a running state. This state is not called the running state because the thread does not always occupy the processor. In particular, for a PC with only one processor, only one runable thread can occupy the processor at any time. Java achieves multi-thread sharing to the processor through scheduling.

● Non-running state (not runnable)

When the following events occur, the thread enters the non-running state.

① The suspend () method is called;

② The sleep () method is called;

③ The thread uses wait () to wait for the condition variable;

④ The thread is in the I/O wait state

● Dead)

When the run () method returns, or another thread calls the stop () method, the thread enters the dead state. Generally, the applet uses its stop () method to terminate all threads it produces.

(3) thread priority

Although we say that threads run concurrently. However, this is often not the case. As mentioned above, when the system only has one CPU, executing multiple threads in a certain order under a single CPU is called scheduling ). Java adopts a simple and fixed scheduling method, namely, fixed priority scheduling. This algorithm is scheduled based on the relative priority of a runable thread. When a thread is generated, it inherits the priority of the original thread. You can modify the priority as needed. If multiple threads are waiting for running at any time, the system selects the highest-priority runable thread for running. A thread can run only when it is stopped, automatically abandoned, or because it becomes a non-running low-priority thread for some reason. If two threads have the same priority, they are run alternately.

The thread scheduling algorithm of the Java real-time system is still mandatory. At any time point, if the state of a thread with a higher priority than other threads changes to a runable state, the real-time system selects this thread to run.

(4) ghost thread

Any Java thread can become a ghost thread. It is a service provider for objects and threads running in the same process. For example, the hotjava browser has a ghost thread called "background image reader", which reads images from the file system or network for the objects and threads that require images. Ghost threads are typical independent threads in applications. It provides services for other objects and threads in the same application. The run () method of the ghost thread is generally infinite loop, waiting for service requests.

(5) thread group

Each Java thread is a member of a thread group. A thread group provides a mechanism for multiple threads to gather in one object and perform overall operations on them. For example, you can use one method to start or suspend all threads in the group. Java thread groups are implemented by the threadgroup class. When a thread is generated, you can specify a thread group or place it in a default thread group by the real-time system. A thread can belong to only one thread group, and cannot be changed when a thread is generated.

Multi-threaded Program

This is not much to say about the benefits of multithreading. However, it also brings some new troubles. It is not too difficult to overcome these troubles as long as you pay special attention when designing the program.

(1) Synchronization thread

Many threads must consider sharing data or coordinating execution status with other threads during execution. This requires a synchronization mechanism. In Java, each object corresponds to a lock. However, Java does not provide separate lock and unlock operations. It is implemented implicitly by the high-level structure to ensure the corresponding operation. (However, we note that the Java Virtual Machine provides separate Monito renter and monitorexit commands to implement the lock and unlock operations .)

The synchronized statement calculates an object reference, attempts to complete the lock operation on the object, and stops processing before the lock operation is completed. When the lock operation completes synchronized, the statement body is executed. The unlock operation is automatically completed after the statement body is executed (whether normal or abnormal. As an object-oriented language, synchronized is often used with methods. A better way is that if a variable is assigned a value by a thread and referenced or assigned a value by another thread, all access to the variable must be in a synchromized statement or synchronized method.

Now let us assume that thread 1 and thread 2 both need to access a data zone and require that thread 1's access be prior to thread 2. In this case, using only synchronized cannot solve the problem. This can be implemented using simaphore in Unix or Windows NT. Java does not. The wait () and Y () mechanisms are provided in Java. Use:

Synchronized Method-1 (...) {Call by thread 1.

Using access data area;

Available = true;

Notify ()

}

Synchronized Method-2 (...) {Invoke call by thread 2.

While (! Available)

Try {

Wait (); wait for every Y ().

} Catch (interrupted exception e ){

}

Using access data area

}

Available is a class member variable and sets the initial value to false. If the available value is false in method-2, wait () is called (). Wait () enables thread 2 to enter a non-running state and unlock it. In this case, method-1 can be called by thread 1. After running notify. Thread 2 is changed from non-running to running. After method-1 is returned. Thread 2 can re-lock the object and execute the command after wait () returns after the lock is successful. This mechanism can also be applied to other more complex situations.

(2) deadlock

If the program has several concurrent threads that compete for resources, it is very important to ensure the balance. System Balancing means that each thread can fully access limited resources during execution. There are no starved or deadlocked threads in the system. Java does not provide a Deadlock Detection mechanism. It is a good choice for most Java programmers to prevent deadlocks. The simplest way to prevent deadlocks is to introduce serial numbers to competing resources. If a thread requires several resources, it must first obtain resources with a small serial number and then apply for resources with a large serial number.

 Summary

Thread is an important part of Java, and multithreading is a feature of Java. Although Java synchronization mutex is not as rich as some systems, using them properly can also achieve satisfactory results.

From: http://www.51testing.com/html/60/n-132760.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.