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 process.

In a system without an OS, programs are executed sequentially. That is, one program is allowed to be executed only after the other program is executed. In a multiprogram environment, multiple programs are allowed to execute concurrently. There are significant differences between these two ways of executing a program. It is this characteristic of concurrent execution of programs that led to the introduction of the concept of processes in operating systems.

Since the concept of a process was introduced in the 1960s, it has always been the basic unit in OS that can own resources and run independently. Until the mid-1980s, people put forward a basic unit smaller than process that can run independently — Thread, trying to use it to improve the degree of concurrent execution of programs in the system, so as to further improve the throughput of the system. Especially after entering the 1990s, the multiprocessor system has been developed rapidly. Threads can better improve the parallel execution of programs than processes, and give full play to the superiority of multiprocessors. Therefore, threads have been introduced in the multiprocessor OS introduced in recent years to improve the performance of OS.

—– The above excerpt from computer Operating System, edited by Tang Xiaodan et al., 3rd edition

(2) The following is the explanation from Zhihu users:

Now that we know what threads and processes are, let’s summarize the concepts for processes and threads:

(3) Process is a running activity of a program in a computer on a data set. It is the basic unit of system resource allocation and scheduling and the basis of operating system structure. In the early process-oriented computer architecture, the process is the basic execution entity of the program. In modern thread-oriented computer architectures, processes are containers for threads. A program is a description of instructions, data and their organizational form, while a process is an entity of the program.

(4) Threads, sometimes called Lightweight processes (LWP), are the smallest unit of program execution flow. A thread is a single sequence control flow in a program. A relatively independent, schedulable unit of execution within a process, which is the basic unit of system independent scheduling and CPU dispatch. The simultaneous running of multiple threads in a single program to accomplish different tasks is called multithreading.

(5) The relationship between process and thread:

Second, Java to achieve multithreading

(1) Inherit Thread and rewrite 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(); // The correct way to start a thread}}Copy the code

Output result:

Thread-0Thread-0Thread-0...
Copy the code

Also, be aware that the start () method, not the run () method, is used to start the thread. If you use the run () method, it will be executed as a normal method.

(2) Implement Runable interface

public class MyRunnable implements Runnable {     @Override    public void run() {        System.out.println("123");    }     public static void main(String[] args) {        MyRunnable myRunnable = new MyRunnable();        Thread thread = new Thread(myRunnable, "t1");        thread.start();    }}
Copy the code

Third, thread safety

Thread-safe concept: a class (object or method) is thread-safe if it consistently behaves correctly when accessed by multiple threads.

Thread safety refers to the locking mechanism used in multi-thread access. When one thread accesses a certain data of the class, it is protected and cannot be accessed by other threads until the thread finishes reading the data. There will be no data inconsistencies or data contamination. Thread insecurity means that data access protection is not provided. Multiple threads may change data successively, resulting in dirty data. Here the locking mechanism is common, such as synchronized

4. Synchronized modifier

(1) synchronized: any object and method can be locked, and the locking code is called “mutually exclusive area” or “critical area”.

(2) Do not use synchronized instances (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();    }}
Copy the code

One result of the output is as follows:

thread3 count:2thread4 count:1thread1 count:2thread2 count:3thread5 count:0
Copy the code

As you can see, the above result is incorrect because multiple threads are operating on the run () method at the same time, modifying count and causing 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();    }}
Copy the code

Output result:

thread1 count:4thread2 count:3thread3 count:2thread5 count:1thread4 count:0
Copy the code

You can see that the difference between code A and code B is the synchronized modifier on the run () method.

The instructions are as follows: When multiple threads access MyThread’s run method and the synchronized modifier is used, the thread is queued up (in CPU allocation order), and a thread wants to execute the synchronized code. The first is to try to obtain the lock. If the lock is obtained, the content of synchronized code body is executed. If the lock cannot be obtained, the thread will continuously try to obtain the lock until it is obtained.

An object has a lock! Multiple threads multiple locks!

What? One lock per object, multiple threads, multiple locks! 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,set num over!" ); } else { num = num - 200; System.out.println(threadName + " tag b,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(); new Thread(new Runnable() { public void run() { multiThread2.printNum("thread2", "b"); } }).start(); }}Copy the code

Output result:

thread1 tag a,set num over! thread1 tag a, num = 100thread2 tag b,set num over! thread2 tag b, num = 0Copy the code

If multiple objects use the same lock, the result of the above execution should be: thread2 tag b, num = -100, so each object owns the lock of that object.

The lock acquired by the keyword synchronized is an object lock, rather than a piece of code or method as a lock. Therefore, in the above example code C, whichever line executes the synchronized method first, that thread holds the lock of the object that the method belongs to. Two objects, the thread obtains two different locks of different objects. They don’t influence each other.

So, in a normal scenario, there must be a situation where all objects operate on a variable called count. So how do we implement that? Static (D); static (D); static (D); static (D); static (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,set num over!" ); } else { num = num - 200; System.out.println(threadName + " tag b,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 thread1 has finished!" ); new Thread(new Runnable() { public void run() { multiThread2.printNum("thread2", "b"); } }).start(); }}Copy the code

Output result:

thread1 tag a,set num over! Thread1 tag a, num = 100 Wait 5 seconds to ensure that thread1 has finished executing! thread2 tag b,set num over! thread2 tag b, num = -100Copy the code

Methods that are not static are locked on each object. Methods that are not static are locked on each object.

Object lock synchronization and asynchrony

(1) The concept of synchronized is sharing, we should know that the word “sharing”, if it is not a shared resource, there is no need to synchronize, that is, there is no need to lock; Synchronization is for thread safety. In fact, for thread safety, two basic characteristics need to be met: atomicity and visibility;

“Asynchronization” is the concept of being independent and not restricted to each other, or having no relationship with each other.

(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();    }}
Copy the code

Method () in the above code is the asynchronous method.

Conclusion:

Thank you for reading this article, but also for you to prepare advanced Java architecture information, need friends can follow the wechat public number [Java programmers gathering] to obtain architecture information.