1. Processes and threads

1.1 Concepts of processes and threads

  • A process is an application (1 process is a piece of software).

  • A thread is an execution scenario/execution unit in a process.

1.2 Relationship between Processes and threads

Comparison between process A and process B:

The two processes are independent and do not share resourcesCopy the code

Compare thread A with thread B:

Thread A and thread B share heap memory and method area memory. But stack memory is independent, one stack per thread. If you start 10 threads, there will be 10 stack Spaces, each stack and each other, each of which does not interfere with each other, each of which executes its own, that is multi-threaded concurrency.Copy the code

1.3 The relationship between threads and main methods

After using multithreading, does the program end when main ends?

The main method ends only when the main thread ends, the main stack is empty, and other stacks (threads) may still be pushing the stack.Copy the code

1.4 Single-core CPU, can do multithreading concurrency?

True multithreaded concurrency is fine on a multi-core CPU. A single-core CPU means only one brain: true multithreaded concurrency cannot be achieved, but it can be achieved to give the impression of "multithreaded concurrency". For a single-core CPU, only one thing can actually be processed at a certain point in time, but because of the extremely fast processing speed of the CPU, multiple threads are frequently switched between execution, with the feeling that many things are doing !!!!!Copy the code

2 Two ways to implement threads

2.1 How to inherit the Thread class

Steps:

1. Write a class that inherits java.lang.Thread directly and overrides the run method. Call the start() method of the thread objectCopy the code

Code examples:

2.2 How to Implement the Runnable Interface

This is a more flexible way to implement the interface

Steps:

Write a Runnable class that implements the java.lang.Runnable interface and overrides the run method. Create a runnable object and wrap it as a Thread object using the constructor of the Thread classCopy the code

Code examples:

Implement the interface with an anonymous inner class:

3. Thread life cycle

4. Some methods of threading

4.1 Basic Methods

Get the current thread object

Thread t = Thread currentThread(); The return value t is the current threadCopy the code

Get the name of the thread object

String name = thread object.getName ();Copy the code

Change the name of the thread object

Thread object.setName (" thread name ");Copy the code

The default name of the thread object

Thread-0
Thread-1
Thread-2
Thread-3
......
Copy the code

The above three methods are demonstrated:

4.2 Thread sleep method

4.2.1 Use of sleep method

static void sleep (long millis)

1, static method: thread.sleep (1000); 3, effect: let the current thread sleep, enter the "blocking state", give up occupy CPU time slice, let other threads use. The thread.sleep () method does this by executing a specific piece of code at a specific time interval.Copy the code

Code demo:

4.2.2 Interview questions with sleep() method

4.2.3 Ending the sleep of a thread

Interrupt method

Threadobject. Interrupt (); Depending on the way Java's exception handling mechanism worksCopy the code

Code demo:

4.3 Terminate thread execution reasonably

5. Thread scheduling

5.1 Common thread scheduling models

1. Preemptive scheduling model:

Whichever thread has a higher priority has a higher chance of grabbing CPU time slices. Java uses the preemptive scheduling model.Copy the code

2. Homogeneous scheduling model:

Allocate CPU time slices evenly. Each thread occupies the same amount of CPU time slice. Equally distributed, all equal. In some programming languages, thread scheduling models take this approach.Copy the code

5.2 Methods related to thread scheduling

1. Example method:

Void setPriority(int newPriority) Set the priority of the thread int getPriority() Obtain the priority of the thread Lowest priority 1 The default priority is 5 Highest priority 10 Obtain more CPU time chips with higher priorities. (Not quite, though; there are plenty.)Copy the code

2. Static method:

The static void yield() method suspends the currently executing thread object and executes other threads. The yield() method is not a blocking method. Makes the current thread yield to another thread. The execution of the yield() method causes the current thread to return from the "running" state to the "ready state." Note: it is possible to grab it again after getting ready.Copy the code

3. Example method:

Void join() extends Thread {public void doSome(){MyThread2 t = new MyThread2(); t.join(); // The current thread blocks, and t thread executes until T thread terminates. The current thread can continue. } } class MyThread2 extends Thread{ }Copy the code

Thread priority:

Make way for threads:

Thread merging:

6. (Emphasis) Thread safety

6.1 Conditions for thread-safe data

Three conditions: multithreading concurrency, shared data, shared data modification behavior.

6.2 Solutions to thread safety problems

6.2.1 Thread Synchronization Mechanism Solves security problems

Thread synchronization mechanism: threads are queued for execution (not concurrent), using queued execution to solve thread safety problems.

If the thread is queued, some efficiency will be sacrificed. Data security is the first, only data security, we can talk about efficiency.Copy the code

6.2.2 Asynchronous programming model and synchronous programming model

Asynchronous programming model:

T1 doesn't care about T2, t2 doesn't care about T1, and nobody needs to wait for anyone. This programming model is called the asynchronous programming model. In essence: multi-threaded concurrency (efficient). Asynchrony is concurrency.Copy the code

Synchronous programming model:

Thread T1 and thread T2, when thread T1 is executing, they have to wait for thread T2 to finish, or when thread T2 is executing, they have to wait for thread T1 to finish, and that's the synchronous programming model. Inefficient, threads queue execution. Synchronization is queuing.Copy the code

7. Three variables are thread-safe

Instance variable: in the heap. Static variables: in the methods area. Local variables: on the stack. Local variables are never thread-safe. Because local variables are not shared. (One stack per thread.) Local variables are in the stack. So local variables are never shared. The instance variable is in the heap, and the heap only has one. Static variables are in the method area, and the method area has only one. Both heap and method areas are shared by multiple threads, so there may be thread safety issues. Local variables + constants: There are no thread-safety issues. Member variables: There can be thread safety issues.Copy the code
To use local variables: : StringBuilder is recommended. Because local variables are not thread-safe, StringBuilder is chosen. Stringbuffers are inefficient.Copy the code

8. Thread synchronization solves thread safety

8.1 Use the thread synchronization mechanism to solve the thread security problem.

8.1.1 Syntax of thread Synchronization:

Synchronized (){// thread synchronizes code blocks. } Note: synchronized () parentheses must be shared by multiple threads in order to achieve multi-thread queuing.Copy the code
What is written in ()? Depending on which threads you want to synchronize, let's say you have T1, T2, T3, T4, and T5, and you just want t1, T2, t3 to queue, t4, t5 to queue. How to do? Be sure to write a t1 t2 T3 shared object in (). This shared object is not shared for T4, T5.Copy the code
In the Java language, every object has a "lock," which is how the code that marks synchronized () is executed: assuming that t1 and T2 threads are concurrent, the following code must be executed first; 1. If T1 executes first and encounters synchronized, it will automatically find the object lock of "shared object" and occupy it; 2. Execute the synchronization code block to release the lock. 3. The waiting T2 thread owns the lock and performs the same operation as the T1 threadCopy the code

8.1.2 Example 1: Simulate two threads to withdraw money from the same account simultaneously

Account class

Thread class

The test program

8.2 Use synchronized on instance methods

When to use:

This approach is recommended if the shared object is this and the code block that needs to be synchronized is the entire method bodyCopy the code

The advantages and disadvantages:

Disadvantages: 1, synchronized appears in the instance method, must lock this, inflexible 2, synchronized appears in the instance method, the synchronization is the whole method body, will expand the scope of synchronization access, the execution efficiency is reduced, not commonly used advantages: code to write less, concise.Copy the code

8.3 Use synchronized in a static method

Use synchronized on static methods to indicate class locking. There is always only one class lock. Even if 100 objects are created, there is only one lock of that type.Copy the code

8.4 (Summary) Synchronized

The first kind of synchronized code block (flexible){synchronized code block; } Second: using synchronized on instance methods means that the shared object must be this and that the synchronized code block is the entire method body. The third way is to use synchronized on static methods to represent class locking. There is always only one class lock. Even if 100 objects are created, there is only one lock of that type. Object locks: 1 lock for 1 object, 100 locks for 100 objects. Class lock: 100 objects, maybe just 1 class lock.Copy the code

9. Deadlock (Master)

Deadlock:

Synchronized is best avoided as it can cause deadlocks and can be difficult to debugCopy the code

Code demo:

10. Daemon threads

10.1 Daemons

Java language thread is divided into two categories: one is: user thread one is: daemon thread (background thread), which is representative: garbage collection thread (daemon thread). Daemon thread features: the general daemon thread is an infinite loop, all user threads as long as the end, the daemon thread automatically terminated. Note: The main thread method is a user thread. What are daemon threads used for? The system automatically backs up data at 00:00 every day. This requires the use of a timer, and we can set the timer as a daemon thread. I watched it all the time and backed it up before 00:00.Copy the code

10.2 Setting daemons

Thread object. SetDaemon (true);Copy the code

Setting up the daemon thread:

11. The timer

Functions of timer:

To execute a specific program at a specific time interval.Copy the code

Timer Settings:

Timer Timer = new Timer(); 2. Specify timer.schedule(scheduled task, first execution time, interval of execution); timer.schedule(new LogTimerTask(), firstTime, 1000 * 10); Class LogTimerTask extends TimerTask {public void run() {// Write a task that needs to be executed}}Copy the code

Set timer:

12. A third way to implement threads

12.1 Implementing the Callable Interface (New in JDK8)

A thread that implements the Callable interface can retrieve the return value of the thread. But it gets clogged and becomes less efficientCopy the code

Steps:

Write a runnable class that implements the java.lang.Callable interface and overrides the Call method. Create a FutureTask class and pass the runnable class into the FutureTask constructor. 3. Create a Thread class. 4. The starting thread calls the start() method of the thread object. 5Copy the code

Code examples: