Analysis of multi-threaded java

zhaozj2021-02-08  258

Analysis of multi-threaded java

Author: Ma Guanghui

Source, and characteristics of a java language

At this era of high-speed information, the merchants have made information, products to the Internet International Interconnect. Behind these unusual web pages, you have to be fully functional, safe and reliable programming languages, Java is well deserved. Java is a powerful new programming language developed by Sun Microsystem. It is a programming language that is unrelated to the platform. It is a simple, distributed, interpreted, keys, secure, structural, highly excellent, multi-threaded, dynamic, language.

After Java, after the introduction, Java is simple, the code is efficient, and the portability is strong, and it is very popular among the majority of computer programming people. The Java language is a revolutionary programming language on the Internet. It has strong animations, multimedia and interactive features that have enabled World Web into a new era. Java language is very similar to C , which can be used to create secure, portable, multi-threaded interactive programs. In addition, the procedures developed by Java are independent of the platform, which can be run on a variety of platforms. Background development is an efficient and practical programming method. People can only see, for example, pattern, calculated results before the screen. In fact, the operating system often schedules some events in the background, the flow of the management program, etc. For example, the stack in the operating system, the resource allocation and management, memory creation, access, management, etc. It can be said that it will not be raised. Let's talk about multithreading.

Two Java multi-threading theory

2.1 introduction

The multi-threaded features provided by Java allows multiple small tasks in a program. Threads sometimes referred to as a small process is a small independent process you have eigned out in a large process. Because of the multi-threaded technology implemented by Java, it is more important than C and C . The greater benefits of multi-threading are better interaction performance and real-time control performance. Of course, real-time control performance depends on the system itself (UNIX, Windows, Macintosh et al.), Which is better than single-threading, and performance. Traditional programming environments are usually single-threaded, since Java is multithreaded. Although multi-thread is a strong and smart programming tool, it is not easy to use well, and there are many traps, even if the programming older is inevitable. In order to better understand the thread, use the office staff as a metaphor. The office staff is like the CPU, and work according to the higher-level instructions, it is like performing a thread. In a single threaded environment, the way each program is written and executed is that the program considers only one processing order. Using our metaphor, it is like an office staff from the end to the end, not born and distracting, and only arranges a job. Of course, there is only one task in actual life, and more common is that staff should do a few things at the same time. The boss handed the work to the staff, hoping that the staff would do this, and then do some jobs, and so on. If a task can't do it, such as the staff waiting for another department, the staff puts this work aside and transfer to another job. In general, the boss hopes that the staff of the staff has some progress every day. This introduces the concept of multithreading. Multi-threaded programming environments are very similar to this typical office, and a few tasks or threads are assigned to the CPU. Like office staff, computer CPUs can actually do a few things at the same time, but assign time to different threads, making each thread a bit progressive. If a thread is unable, such as the keyboard input required by the thread is not yet, then transfer to another thread. Typically, the CPU switching between the thread is very rapid, making people feel that all threads are carried out simultaneously.

Any handling environment, whether it is single-threading or multi-threading, there are three key aspects. The first is the CPU, which actually performs computer activity; the second is the code of the executed program; the third is the data of the program operation.

In multi-threaded programming, each thread provides a thread behavior with an encoding, and the encoding operation is supplied with the data. Multiple threads can handle the same coding and data at the same time, and different threads may also have different coding and data. In fact, the encoding and data parts are quite independent, and they can be provided to threads when needed. Therefore, several threads are often used to use the same coding and different data. This idea can also be metaphor with office workers. Accounting may be a departmental account or several or several departments. The task of any case is the same program code, but the data of each department is different. Accounting may have to do the entire company, there are several tasks, but some data is shared because the company accounts need data from each department. The multi-threaded programming environment is used to hide the fact that the CPU is between task switches. The model allows for pretending to have multiple available CPUs. In order to establish another task, the programmer requires another virtual CPU indicating that it starts to perform a block with a data group. Let's build a thread.

Establish a thread

It is not difficult to establish a thread in Java, the three things you need: the code, the data operated by the code and the virtual CPU executing the code. The virtual CPU is packaged in the example of the Thread class. When you create a Thread object, you must provide the data processed by the code and the code processed. Java's object-oriented model requires program code to write only members of the class. Data can only exist as a member of the automatic (or local) variable or class in the method. These rules require that the code and data provided by the thread should appear in the form of a class of instances.

Public Class Simplerunnable IMPLEMANTS RUNABLE {

PRIVATE STRING MESSAGE;

Public static void main (string args []) {

Simplerunnable r1 = new simplerunnable ("hello");

Thread T1 = New Thread (R1);

T1.Start ();

}

Public Simplerunnable (String Message) {

THIS.MESSAGE = Message;

}

Public void run () {

For (;;) {

System.out.println (Message);

}

}

}

When the thread starts execution, it is executed in the public void run () method. This method is the starting point of the defined thread execution, as if the application starts from the main (), the applet begins like init (). The local data for thread operation is a member of the object that is incoming the thread.

First, the main () method constructs an example of the Simplerunnable class. Note that the instance has its own data, here is a string, which is initialized to "Hello". Since instance R1 is incorporated into the Thread class constructor, this is the data processed at the thread. The code executed is an example method Run ().

2.2 Management of threads

Both single-threaded programs have a main executive, which runs some code, after the program ends execution, it just exits, the program simultaneously ends. In Java, we have to get the same response and must be changed slightly. Only when all threads exit, the program can end. As long as there is a thread that is running, the program cannot exit. Threads include four states: New, Running, Wait (waiting) and DONE. When you create a thread for the first time, it is located in the New Status. In this state, you cannot run the thread, you can only wait. The thread is then started or sent by the method START or sent to the DONE. The thread in DONE has ended, which is the last state of the thread. Once the thread is in this state, it cannot appear again, and when all threads in the Java virtual machine are located in the DONE state, the program is forcibly suspended. All threads currently executing are located in the Running state. In some ways, the processor's execution time is divided into time films, and each thread located in the Running state is running, but in a given time Each system processor can only run a thread. Unlike threads located in the Running state, for some reason, threads already in the WAITING state can be removed from a set of executable threads. If the execution of the thread is interrupted, return to the wait. Use a variety of ways to interrupt a thread. Threads can be suspended, waiting on system resources, or inform you to go to sleep. The thread of this state can return to the Running state, and can also be sent to the DONE state by method STOP.

description

Valid state

Destination status

Start ()

Start executing a thread

New

Running

STOP ()

End to execute a thread

New or Running

DONE

Sleep (long)

Suspend a period of time, this time is a given millisecond

Running

Wait

Sleep (long, int)

Temporary to the moment, you can get to nanoseconds

Running

Wait

Suspend ()

Hang

Running

Wait

ResMe ()

Recovery

Wait

Running

Yield ()

Clearly give up execution

Running

Running

2.3 Scheduling of thread

The order of thread operation and the number of times obtained from the processor depend primarily dependent on the developer, and the processor assigns a time film for each thread, and the running operation cannot affect the entire system. The system or preemptive of the processor thread or is non-seizure. The preemptive system will run the highest priority thread in any given time, all threads in the system have their own priority. Thread.norm_Priority is the default value of the thread, the Thread class provides the setPriority and getPriority methods to set and read priority, using the setPriority method to change the importance of threads in the Java virtual machine, which calls an integer, and the class variable thread. Min_Priority and Thread.max_Priority determines the effective range of this integer. The Java virtual machine is a preemptive, which ensures the highest priority thread. In the Java virtual machine, we change the priority of a thread to the highest, then he will replace the current running thread unless this thread is running or placed in a WAITING state by a hibernation command. time. If you encounter two priority threads, the operating system may affect the execution order of the thread. And this difference depends on the concept of time slians.

Managing several threads is not a real problem, what is it managed for hundreds of threads? Of course, you can perform each thread by loop, but this is obviously lengthy and boring. Java creates a thread group. The thread group is a line of threads, and each group contains the number of threads that are not limited to name each thread and can perform (SUSPEND) and stop (STOP) throughout the thread group. 2.4 Signal Sign: Protecting other shared resources

This type of protection is called a mutex. There is only one thread to read or modify this data value. When processing the file, especially the information database, the read data is always more than write data. According to this, the program can be simplified. Here, an example, assumes a database of employee information, including information such as an employee's address and phone number, sometimes modified, but more or read data, so prevent data from being destroyed or arbitrarily deleted. We introduce the concept of the previous mutex, allowing a read lock and write lock (Write Lock), which can determine the person who has the right to read the data as needed, and when someone wants to write data, there must be Mutually exclusive lock, this is the concept of signal logo. There are two states in the signal flag, first which is the EMPTY () state, indicating that there is no thread being read or written, can accept the read and write request, and provide a service immediately; the second state is the reading () state, indicating that the thread is Read the information from the database and record the number of threads for read operations. When it is 0, return to the EMPTY state, and a write request will cause this thread to enter the waiting state.

You can only enter the Writing state from the EMPTY state. Once you enter the Writing state, other threads cannot write, any write or read request must wait until this thread completes the write operation, and the process in the waiting status must always wait until the end of the write operation. . After completing the operation, return to the EMPTY state, send a notification signal, waiting for the thread to be served.

The following is implemented

Class semaphore {

Final static int Empty = 0;

Final static int = 1;

Final static int Writing = 2;

Protected int 2 = Empty

protected int = 0;

Public synchronized void readlock () {

IF (state == Empty) {

State = Reading;

}

Else if (state ==read) {

}

ELSE IF (state == Writing) {

While (state == Writing) {

Try {wait ();

Catch (InterruptedException E) {;

}

State = Reading;

}

READCNT ;

Return;

}

Public synchronized void writelock () {

IF (state == Empty) {

State = Writing;

}

Else {

While (state! = empty) {

Try {wait ();

Catch (InterruptedException E) {;

}

}

}

Public synchronized void readunlock () {

Readcnt--

IF (readcnt == 0) {

State = EMPTY;

NOTIFY ();

}

}

Public synchronized void writeunlock () {

State = EMPTY;

NOTIFY ();

}

}

It is now a program for test signal markers:

Class Process Extends thread {

String OP;

Semaphore Sem;

Process (String Name, String Op, Semaphore Sem) {

Super (Name);

THIS.OP = OP;

THIS.SEM = SEM;

START ();

}

Public void run () {

IF (Op.comPareto ("Read") == 0) {

System.out.println ("Trying to Get Readlock:" GetName ());

Sem.readlock ();

System.out.println ("Read Op: GetName ());

Try {SLEEP ((int) (Math.random () * 50);

Catch (InterruptedException E) {;

System.out.println ("Unlocking Readlock:" GetName ());

SEM.Readunlock ();

}

Else IF (Op.comPareto ("Write") == 0) {

System.out.println ("Trying to Get WriteLock:" GetName ());

Sem.writelock ();

System.out.println ("Write Op:" GetName ());

Try {SLEEP ((int) (Math.random () * 50);

Catch (InterruptedException E) {;

System.out.println ("Unlocking WriteLock:" GetName ());

Sem.writeunlock ();

}

}

}

Public class testsem {

Public static void main (String Argv []) {

Semaphore Lock = New Semaphore ();

NEW Process ("1", "Read", LOCK;

NEW Process ("2", "Read", LOCK;

New Process ("3", "WRITE", LOCK;

NEW Process ("4", "Read", LOCK;

}

}

The TestSem class starts from the four instances of the Process class, it is a thread, used to read or write a shared article

Part. The Semaphore class guarantees that the access does not undermine the file, execute the program, the output is as follows:

Trying to Get Readlock: 1

READ OP: 1

Trying to Get Readlock: 2

READ OP: 2

Trying to get WriteLock: 3

Trying to Get Readlock: 4

READ OP: 4

UNLOCKING READLOCK: 1

UNLOCKING READLOCK: 2

UNLOCKING READLOCK: 4

Write OP: 3

Unlocking Writelock: 3

As seen from this,

2.5 dead locks and how to avoid dead locks:

In order to prevent concurrent access of the data item, the data item standard should be dedicated, and only the synchronization area of ​​the instance method of the class itself. In order to enter the key area, the thread must obtain the lock of the object. Assume that the thread must exclude data to access two different objects, you must take a different lock from each object. Now, it is assumed that another thread must alone access to these two objects, and the process must get these two locks to enter. Due to two locks, the programming may have a deadlock if it is not careful. Suppose the first thread acquires the lock of the object A, ready to take the lock of the object B, and the second thread gets the lock of the object B, and the lock is ready to take object A, and the two threads cannot be entered because both cannot leave Entering synchronization blocks, both of them cannot give up the currently holding lock. Avoid death locks to be carefully designed. Threads When a prerequisites are blocked, if the lock mark is required, the thread is not allowed to stop the condition of the condition. If you want to get multiple resources, such as the lock of two different objects, you must define the order of the acquisition. If the locks of objects A and B are always obtained in alphabetical order, they do not appear in front of starving conditions. Excellent and shortcomings of three java multi-threaded

Since Java's multi-threaded function is complete, all kinds of case masks come, it also brings advantageous benefits. The greater benefits of multi-threading are better interaction performance and real-time control performance. Of course, real-time control performance depends on the system itself (UNIX, Windows, Macintosh et al.), Which is better than single-threading, and performance. Of course, a good programming language is definitely inevitable. Since the multi-thread has not fully utilized this feature of the basic OS. This has been mentioned earlier. For different systems, the above programs may have a distinct result, which makes the programmer feel confused. I hope that in the near future, Java multi-line can make full use of the operating system, reducing the confusion of the programmer. I am looking forward to Java better.

Four references:

Author Philip Heller Simon Roberts

Peter Seymour Tom McGinn

1

,

Java Senior Development Guide

This book is divided into four parts, the first part of the basic articles, introduces the Java environment, apparatus and applications, components, arrangement managers, and transplants. The second part of the advanced issues introduces graphics, threads, animations, files, streams, networking, database access, distributed objects, and protocol processors. Part III New API introduces new features of JDK V1.1. The Group IV has introduced the API list, FAQ, etc. For multi-threaded parts, describes what is thread, detailing the thread mechanism in Java, specifically discusses the establishment and control of the Java thread and the meaning of the AWT event processor thread, and the thoughts related to threads in various environments The actual CPU is less than the thread scheduling and interaction between threads and threads, and raises a lot of instances.

Michaeld.thomas Pratikr.patel

Aland.hudson Donalda.ball JR

2, Java for Internet Programming Technology

This book is divided into five. The first introduction to the concept of Java language; the second introduction to the composition of Java Applete, grammar, semantic, interface, etc .; third introduction to Java programming advanced technology; fourth introduction Java and Internet network; the fifth article introduction four Application. For advanced thread portions, the process of creating threads is described in detail, and discusses issues such as how to share resources.

Five, FAQ

1, give Java Next definition?

It is a simple, distributed, interpreted, keys, secure, structural, highly excellent, multi-threaded, dynamic, language.

2, what is applet?

It is a small program that can be embedded in the web home page. It is a powerful, universal, pure, independent, unrelated to platform.

3. What functions have virtual machines? Many basic functions, such as string operation tools, graphics and interface routines, basic data structures, and mathematical functions. This makes it a requirement for the responsibility of the alarm wall.

4, WAIT () and Notify () are the THREAD class?

They are not a THREAD class, which is included in the java.lang.Object class.

5. Three elements consisting in java:

The first is the CPU, which actually performs computer activity; the second is the code of the executed program; the third is the data of the program operation.

6. How to build a thread in Java

See Section 2.1 to establish a thread.

7. There are several ways to manage threads:

See the management of the section 2.2.

8. What is the measures usually taken by thread synchronization?

Monitor: Protect shared variables;

Signal logo: Protect other shared resources;

Avoid death.

9. What is the role of thread group in Java?

The thread group is a line of threads, and the number of threads contains unrestricted can name each thread and can perform suspends over the entire thread group. (STOP) operation.

Also used for the process of Java operating environment and security between threads.

10. What is the benefit of creating a thread with the Runnable interface?

It defines a standard framework for classes, and the Runnable interface specifies a method that has already been implemented - RUN method.

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

New Post(0)