Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Analysis of how to realize JAVA Multithreading

2025-04-10 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

In this issue, the editor will bring you a brief analysis of how to achieve JAVA multithreading. The article is rich in content and analyzes and narrates it from a professional point of view. I hope you can get something after reading this article.

Analysis of multithreading in JAVA

I. the origin and characteristics of JAVA language

In this era of high-speed information, businesses have put information and products on the Internet international interconnection web pages. Behind these unusual web pages, Java deserves to be a fully functional, secure and reliable programming language. Java is a powerful new programming language developed by Sun Microsystem. Is a platform-independent programming language. It is a simple, object-like, distributed, interpreted, key-strong, secure, structurally neutral, portable, excellent performance, multithreaded, dynamic, language.

Since its advent, Java has been favored by the majority of computer programmers because of its simple programming, efficient code and strong portability. Java is a revolutionary programming language on Internet. It has powerful animation, multimedia and interactive functions. It makes World Web enter a new era. The Java language is very similar to C++ in that it can be used to create secure, portable, multithreaded interactive programs. In addition, programs developed with Java have nothing to do with the platform and can be run on a variety of platforms. Background development is an efficient and practical programming method. People can only see such as patterns, calculation results and so on in front of the screen. In fact, the operating system is often in the background to schedule some events, the flow of management programs, and so on. For example, the stack in the operating system, resource allocation and management between threads, memory creation, access, management and so on. It can be said that the act is not grand.

Second, the multithreading theory of JAVA

2.1 introduction

The multithreading function provided by Java makes it possible to perform multiple small tasks in a program at the same time. A thread sometimes calls a small process a small independent process separated from a large process. Because of the multithreading technology implemented by Java, it is more robust than C and C++. The greater benefit of multithreading is better interaction performance and real-time control performance. Of course, the performance of real-time control also depends on the system itself (UNIX, Windows,Macintosh, etc.), which is better than single thread in terms of development difficulty and performance. Traditional programming environments are usually single-threaded, because JAVA is multithreaded. Although multithreading is a powerful and dexterous programming tool, it is not easy to use it well, and there are many pitfalls that even veteran programmers will inevitably misuse. In order to better understand threads, use office workers as an analogy. Office workers are like CPU, doing their work according to their superiors' instructions, just like executing a thread. In a single-threaded environment, each program is written and executed in such a way that only one processing order is considered at any one time. To use our analogy, it is like an office worker who is undisturbed and distracted from beginning to end and arranges only one job. Of course, in real life, it is very difficult for staff to have only one task at a time, and it is more common for staff to do several things at the same time. The boss handed over the work to the staff, hoping that the staff would do this work, do some more work, and so on. If a task cannot be done, such as a staff member waiting for information from another department, the staff member puts the work aside and moves on to another job. Generally speaking, the boss wants the staff to make some progress every day in the tasks at hand. This introduces the concept of multithreading. The multithreaded programming environment is very similar to this typical office, with several tasks or threads assigned to CPU at the same time. Like office workers, a computer CPU can't actually do several things at the same time, but instead allocates time to different threads, making each thread make some progress. If one thread cannot proceed, for example, the keyboard input required by the thread has not been obtained, it moves on to the work of another thread. In general, CPU switches between threads so quickly that it feels as if all threads are running at the same time.

Any processing environment, whether single-threaded or multithreaded, has three key aspects. The first is CPU, which actually carries out computer activities; the second is the code of the executed program; and the third is the data of the program operation.

In multithreaded programming, each thread uses coding to provide the behavior of the thread and data to provide encoded operations. Multiple threads can process the same encoding and data at the same time, and different threads may have different encodings and data. In fact, the coding and data parts are quite independent and can be provided to the thread when needed. So it is often several threads that use the same encoding and different data. This idea can also be compared with office workers. Accountants may have to do accounts for one department or for several or more departments. In any case, the accounting task is the same program code, but the data of each department is different. The accountant may have to do the accounting for the entire company, and there are several tasks, but some data is shared because the company account needs data from various departments.

The multithreaded programming environment uses a convenient model to hide the fact that CPU is switching between tasks. The model allows you to pretend that there are multiple CPU available. To set up another task, the programmer asks for another virtual CPU, instructing it to start executing a segment with a data set. Let's set up a thread.

Set up a thread

It is not difficult to set up threads in JAVA, and there are three things you need: the code that executes, the data that the code operates on, and the virtual CPU that executes the code. The virtual CPU is wrapped in an instance of the Thread class. When you create a Thread object, you must provide the code that is executed and the data that the code processes. The object-oriented model of JAVA requires that program code can only be written as member methods of a class. Data can only exist as a member of an automatic (or local) variable or class in a method. These rules require that the code and data provided to the thread should be in the form of instances of the class.

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 a thread starts execution, it executes in the public void run () method. This approach is the starting point for the execution of defined threads, just as the application starts with main () and Mini Program starts with init (). The local data of the thread operation is a member of the object passed in to the thread.

First, the main () method constructs an instance of the SimpleRunnable class. Note that the instance has its own data, here is a String, initialized to "Hello". Because the instance R1 is passed into the Thread class constructor, this is the data processed by the thread at run time. The code executed is the instance method run ().

2.2 Thread management

A single-threaded program has a main executor that runs some code, and when the program finishes executing, it exits and the program ends running at the same time. To get the same response in JAVA, we have to change it a little bit. The program ends only when all threads exit. As long as a thread is running all the time, the program cannot exit. A thread consists of four states: new (start), running (run), wait (wait), and done (end). The first time a thread is created, it is in the new state, where the thread cannot be run and can only wait. Then, the thread either starts with the method start or is sent to the done state, and the thread in done has finished execution, which is the last state of the thread. Once the thread is in this state, it cannot reappear, and when all threads in the JAVA virtual machine are in the done state, the program is forcibly aborted. All the threads currently executing are in the running state, and the execution time of the processor is divided into time slices in some way between programs. Each thread in the running state can run, but each system processor can only run one thread at a given time. Unlike threads in running state, threads that are already in waiting state can be removed from a set of executable threads for some reason. If the execution of the thread is interrupted, it returns to the waiting state. You can interrupt a thread in many ways. Threads can be suspended, waiting on system resources, or told to go to sleep. The thread in this state can return to the running state, or it can be sent to the done state by the method stop

Method

Description

Effective state

Destination state

Start ()

Start executing a thread

New

Running

Stop ()

End execution of a thread

New or running

Done

Sleep (long)

Pause for a given millisecond

Running

Wait

Sleep (long,int)

Pause for a moment, it can be accurate to nanosecond

Running

Wait

Suspend ()

Suspend execution

Running

Wait

Resume ()

Resume execution

Wait

Running

Yield ()

Explicitly abandon execution

Running

Running

2.3 scheduling of threads

The order in which threads run and the amount of time obtained from the processor mainly depends on the developer. The processor allocates a time slice to each thread, and the running of the thread does not affect the entire system. The system of processor threads is either preemptive or non-preemptive. The preemptive system will run the highest priority thread at any given time, and all threads in the system will have their own priority. Thread.NORM_PRIORITY is the default value for threads, and the Thread class provides setPriority and getPriority methods to set and read priority. Using the setPriority method can change the importance of threads in the Java virtual machine, which calls an integer, and the class variables Thread.MIN_PRIORITY and Thread.MAX_PRIORITY determine the valid range of the integer. The Java virtual machine is preemptive and ensures that the thread with the highest priority is running. If we change the priority of a thread to the highest in the JAVA virtual machine, it will replace the currently running thread, which will take up all processor time unless the thread ends running or is put into the waiting state by a hibernation command. If you encounter two threads with the same priority, the operating system may affect the execution order of the threads. And the difference depends on the concept of time slicing.

Managing several threads is not a real problem. How does it manage hundreds of threads? Of course, each thread can be executed through a loop, but this is obviously tedious and tedious. JAVA created the thread group. A thread group is a pedigree group of threads. Each group contains an unlimited number of threads. Each thread can be named and can perform operations such as Suspend and Stop in the entire thread group.

2.4 signal flag: protect other shared resources

This type of protection is called a mutex. Only one thread can read or modify this data value at a time. When processing files, especially information databases, more data is always read than written. According to this situation, the program can be simplified. As an example, suppose there is a database of employee information, including employee addresses and phone numbers, which sometimes needs to be modified, but more data should be read, so as far as possible to prevent the data from being corrupted or arbitrarily deleted. We introduce the previous concept of mutex, which allows a read lock (red lock) and write lock (write lock) to determine who has the right to read data as needed, and when someone wants to write data, there must be a mutex, which is the concept of signal flags. The signal flag has two states, the first is the empty () state, which indicates that no thread is reading or writing, can accept read and write requests, and provides service immediately; the second state is reading () state, which indicates that a thread is reading information from the database and records the number of threads reading. When it is 0, it returns the empty state, and a write request will cause the thread to enter the waiting state.

You can only enter the writing state from the empty state. Once you enter the writing state, no other thread can write, any write or read request must wait until the thread completes the write operation, and the process in the waiting state must wait until the write operation is finished. After completing the operation, return to the empty state, send a notification signal, and the waiting thread will be served.

The following implementation of this signal flag

Class Semaphore {

Final static int EMPTY=0

Final static int READING=1

Final static int WRITING=2

Protected int state=EMPTY

Protected int readCnt=0

Public synchronized void readLock () {

If (state==EMPTY) {

State=READING

}

Else if (state==READING) {

}

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 (statecraft empoly) {

Try {wait ();}

Catch (InterruptedException e) {;}

}

}

}

Public synchronized void readUnlock () {

ReadCnt--

If (readCnt==0) {

State=EMPTY

Notify ()

}

}

Public synchronized void writeUnlock () {

State=EMPTY

Notify ()

}

}

Now is the program to test the signal flag:

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

Catch (InterruptedException e) {;}

System.out.println ("Unlocking readLock:" + getName ())

Sem.readUnlock ()

}

Else if (op

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 with four instances of the process class, which is a thread that reads or writes a shared file. The Semaphore class ensures that the access will not destroy the file, execute the program, and 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

You can see from here

2.5 deadlocks and how to avoid deadlocks:

To prevent concurrent access to data items, data items should be marked as private and accessed only through the synchronization area of the instance methods of the class itself. In order to enter the critical area, the thread must acquire the lock of the object. Assuming that a thread wants to exclusively access the data of two different objects, it must take a different lock from each object. Now suppose that another thread also has exclusive access to these two objects, then the process must get these two locks before it can enter. Because two locks are required, deadlocks can occur if programming is not careful. Suppose that the first thread acquires the lock of object An and is ready to take the lock of object B, while the second thread acquires the lock of object B and is ready to take the lock of object A, and neither thread can enter because neither can leave the synchronization block in which it enters. Neither can give up the lock it currently holds. Avoid deadlocks and carefully design them. When a thread is blocked by a prerequisite, if a lock mark is needed, the stop of the thread itself cannot be allowed to change the condition. If you want to acquire multiple resources, such as locks for two different objects, you must define the order in which the resources are taken. If the locks of objects An and B are always obtained in alphabetical order, the aforementioned starvation conditions will not occur.

Third, the advantages and disadvantages of Java multithreading.

Due to the multithreading function of JAVA, all kinds of situations are masked, and its benefits are obvious. The greater benefit of multithreading is better interaction performance and real-time control performance. Of course, the performance of real-time control also depends on the system itself (UNIX,Windows,Macintosh, etc.), which is better than single thread in terms of development difficulty and performance. Of course, a good programming language will inevitably have its shortcomings. Because multithreading has not made full use of this function of basic OS. As I mentioned earlier, the above programs may produce very different results for different systems, which confuses programmers occasionally.

The above is the editor for you to share how to achieve JAVA multithreading analysis, if you happen to have similar doubts, you might as well refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report