In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-20 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces "the concept of Java thread, process and Synchronized". In daily operation, I believe that many people have doubts about the concept of Java thread, process and Synchronized. The editor has consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of "Java thread, process and Java concept". Next, please follow the editor to study!
I. the concept of process and thread
(1) in the traditional operating system, the program can not run independently, as the basic unit of resource allocation and independent operation is the process.
(2) the following figure is an explanation from Zhihu users:
Through the above general understanding, we have a basic idea of what threads and processes do, so let's summarize the concepts for processes and threads:
(3) Process is a running activity of a program in a computer on a certain data set, the basic unit of resource allocation and scheduling, and the basis of the structure of the operating system. In the early process-oriented computer architecture, the process is the basic execution entity of the program; in the contemporary thread-oriented computer architecture, the process is the container of threads. A program is a description of instructions, data and its organizational form, and a process is the entity of a program.
(4) Thread, sometimes called a lightweight process (Lightweight Process,LWP), is the smallest unit of the program execution flow. A thread is a single sequential control flow in a program. A relatively independent and schedulable execution unit in a process, which is the basic unit of system independent scheduling and dispatching CPU refers to the scheduling unit of running programs. Running multiple threads at the same time to accomplish different tasks in a single program is called multithreading.
(5) the relationship between process and thread:
Second, Java implements multithreading.
(1) inherit Thread and override the run () method
Public class MyThread extends Thread {@ Override public void run () {while (true) {System.out.println (this.currentThread (). GetName ());}} public static void main (String [] args) {MyThread thread = new MyThread (); thread.start (); / / correct way to start a thread}}
Output result:
Thread-0Thread-0Thread-0...
In addition, understand that it is the start () method rather than the run () method that starts the thread, and if you use the run () method, it is a normal method to execute.
(2) implement Runable interface
Public class MyRunnable implements Runnable {@ Override public void run () {System.out.println;} public static void main (String [] args) {MyRunnable myRunnable = new MyRunnable (); Thread thread = new Thread (myRunnable, "T1"); thread.start ();}}
III. Thread safety
Thread safety concept: when multiple threads access a class (object or method) and the class always behaves correctly, then the class (object or method) is thread safe.
Thread safety means that when a thread accesses some data of this class, it uses a locking mechanism to protect it, and other threads cannot access it until the thread has finished reading it. There will be no data inconsistencies or data contamination. Thread unsafe means that it does not provide data access protection, and it is possible that multiple threads change the data successively so that the data obtained is dirty data. The locking mechanisms here are common, such as synchronized
4. Synchronized modifier
(1) synchronized: locks can be placed on any object and method, and the locked code is called "mutex" or "critical zone".
(2) * * do not use * * synchronized instance (code A):
Public class MyThread extends Thread {private int count = 5; @ Override public void run () {count--; System.out.println (this.currentThread (). GetName () + "count:" + count);} public static void main (String [] args) {MyThread myThread = new MyThread () Thread thread1 = new Thread (myThread, "thread1"); Thread thread2 = new Thread (myThread, "thread2"); Thread thread3 = new Thread (myThread, "thread3"); Thread thread4 = new Thread (myThread, "thread4"); Thread thread5 = new Thread (myThread, "thread5"); thread1.start () Thread2.start (); thread3.start (); thread4.start (); thread5.start ();}}
One result of the output is as follows:
Thread3 count:2thread4 count:1thread1 count:2thread2 count:3thread5 count:0
As you can see, the above results are incorrect because multiple threads operate on the run () method at the same time to modify the count, resulting in an error.
(3) * * use * * synchronized instance (code B):
Public class MyThread extends Thread {private int count = 5; @ Override public synchronized void run () {count--; System.out.println (this.currentThread (). GetName () + "count:" + count);} public static void main (String [] args) {MyThread myThread = new MyThread (); Thread thread1 = new Thread (myThread, "thread1"); Thread thread2 = new Thread (myThread, "thread2"); Thread thread3 = new Thread (myThread, "thread3") Thread thread4 = new Thread (myThread, "thread4"); Thread thread5 = new Thread (myThread, "thread5"); thread1.start (); thread2.start (); thread3.start (); thread4.start (); thread5.start ();}}
Output result:
Thread1 count:4thread2 count:3thread3 count:2thread5 count:1thread4 count:0
You can see that the difference between code An and code B is that the run () method is decorated with synchronized.
The explanation is as follows:
When multiple threads access the run method of MyThread, if synchronized modification is used, that multi-thread will be processed in a queued manner (here the queue is determined according to the order in which CPU is assigned). The code in the method in which a thread wants to perform synchronized modification is first to try to acquire the lock, if it gets the lock, executes the contents of the synchronized code body, if it cannot get the lock. The thread will keep trying to acquire the lock until it is acquired, and multiple threads will compete for the lock at the same time, that is, the problem of lock competition will arise.
Fifth, an object has a lock! Multiple threads, multiple locks!
What is it? one object, one lock, multiple threads, multiple locks! First, take a look at the following example code (code C):
Public class MultiThread {private int num = 200; public synchronized void printNum (String threadName, String tag) {if (tag.equals ("a")) {num = num-100; System.out.println (threadName + "tag a dint set num over!");} else {num = num-200; System.out.println (threadName + "tag bjue set num over!") } System.out.println (threadName + "tag" + tag + ", num =" + num);} public static void main (String [] args) throws InterruptedException {final MultiThread multiThread1 = new MultiThread (); final MultiThread multiThread2 = new MultiThread (); new Thread (new Runnable () {public void run () {multiThread1.printNum ("thread1", "a");}} start (); Thread.sleep (5000) System.out.println ("wait 5 seconds to make sure the thread1 has been executed!") ; new Thread (new Runnable () {public void run () {multiThread2.printNum ("thread2", "b");}}) .start ();}}
Output result:
Thread1 tag a moment set num overloaded thread 1 tag a, num = 100 wait 5 seconds to make sure that the thread1 has been executed! Thread2 tag bjournal set num overloaded thread2 tag b, num = 0
As you can see, there are two objects: multiThread1 and multiThread2, and if multiple objects use the same lock, the result of the above execution should be: thread2 tag b, num =-100. therefore, each object owns the lock for that object.
Keyword synchronized acquires object locks instead of treating a piece of code or method as a lock, so which thread in the above example code C first executes the method of the synchronized keyword, that thread holds the lock of the object to which the method belongs, two objects, and the thread acquires different locks of two different objects, and they complement each other.
So, when we are in a normal scenario, there must be a situation where all objects operate on a variable count, so how do we do that? It is very simple to add static. We know that all objects in this class have the same reference to the method or variable modified with static, so that no matter how many objects are instantiated, the method is called, and the code is as follows (code D):
Public class MultiThread {private static int num = 200; public static synchronized void printNum (String threadName, String tag) {if (tag.equals ("a")) {num = num-100; System.out.println (threadName + "tag a dint set num over!");} else {num = num-200; System.out.println (threadName + "tag bjue set num over!") } System.out.println (threadName + "tag" + tag + ", num =" + num);} public static void main (String [] args) throws InterruptedException {final MultiThread multiThread1 = new MultiThread (); final MultiThread multiThread2 = new MultiThread (); new Thread (new Runnable () {public void run () {multiThread1.printNum ("thread1", "a");}} start (); Thread.sleep (5000) System.out.println ("wait 5 seconds to make sure the thread1 has been executed!") ; new Thread (new Runnable () {public void run () {multiThread2.printNum ("thread2", "b");}}) .start ();}}
Output result:
Thread1 tag a moment set num overloaded thread 1 tag a, num = 100 wait 5 seconds to make sure that the thread1 has been executed! Thread2 tag bjournal set num overloaded thread2 tag b, num =-100
As you can see, by adding static modification to both variables and methods, we can achieve the scenario we need, and it also shows that the methods or variables modified by non-static static are locked by an object.
Synchronization and asynchronism of object locks
(1) synchronization: synchronized
The concept of synchronization is sharing. We need to know that if the word "sharing" is not a shared resource, there is no need for synchronization, that is, there is no need for locking.
The purpose of synchronization is for thread safety. In fact, for thread safety, it needs to meet two most basic characteristics: atomicity and visibility.
(2) Asynchronous: asynchronized
The concept of asynchronism is independence, without any restriction on each other, and there is no relationship between the two.
(3) sample code:
Public class MyObject {public void method () {System.out.println (Thread.currentThread (). GetName ());} public static void main (String [] args) {final MyObject myObject = new MyObject (); Thread T1 = new Thread (new Runnable () {public void run () {myObject.method ();}, "T1") Thread T2 = new Thread (new Runnable () {public void run () {myObject.method ();}, "T2"); t1.start (); t2.start ();}}
Method () is the asynchronous method in the above code.
At this point, the study of "the concepts of Java threads, processes, and Synchronized" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.