I. Multithreading

1. An overview of the

Multithreading is a technique that enables concurrent execution of multiple threads from software or hardware.

Running multiple threads simultaneously in a single program to do different work.

2. Concurrency and parallelism

Concurrency: Two or more events occur in the same time period. Parallelism: Two or more events occurring at the same time (simultaneously). Java source programs and bytecode files, called programs, are static concepts.

2) Process refers to an application running in memory, each process has an independent memory space, an application can run multiple processes at the same time; Process is also a procedure of execution process, is the basic unit of the system running procedures; System running a program is a process from creation, operation to extinction process.

3) thread

A thread is a unit of execution in a process that is responsible for the execution of programs in the current process. There is at least one thread in a process. There can be multiple threads in a process, and this application can also be called a multithreaded program.

Create a thread class

1. Inherit the Thread class

Java uses the java.lang.Thread class to represent threads, and all Thread objects must be instances of the Thread class or its subclasses.

The steps to create and start multithreading in Java by inheriting the Thread class are as follows:

Define a subclass of Thread and rewrite the run() method of the class. The body of the run() method represents the task that the Thread needs to complete. Therefore, we call the run() method an instance of Thread subclass. Call the thread object’s start() method to start the thread’s custom thread class:

Public class MyThread extends Thread {public MyThread(String name) {public MyThread(String name) { Specify the name of the thread super(name); } /** * Override public void Override public void Overriderun() {
		for (int i = 0; i < 10; i++) {
			System.out.println(getName()+": Executing!"+i); }}}Copy the code

The test class:

Public class Demo01 {public static void main(String[] args) {public static void main(String[] args) {"New thread!"); // Start a new thread mt.start(); // Execute in the main methodforcyclefor (int i = 0; i < 10; i++) {
			System.out.println("Main thread!"+i); }}}Copy the code

1) Introduction to Thread class

Construction method:

Public Thread(): Allocates a new Thread object.

Public Thread(String name): Allocates a new Thread object with the specified name.

Public Thread(Runnable target): Allocates a new Thread object with the specified target.

Public Thread(Runnable target,String name): Assigns a name to a new Thread object with a specified target.

Common methods:

Public String getName(): Gets the current thread name.

Public void start(): causes the thread to start executing; The Java virtual machine calls the run method of this thread.

Public void run(): The task to be performed by this thread defines the code here.

Public static void sleep(long millis): Suspends the currently executing thread for the specified number of milliseconds.

Public static Thread currentThread(): Returns a reference to the Thread object that is currently executing

2. Implement the Runnable interface

Using java.lang.Runnable is also very common, and we just need to override the run method.

The steps are as follows:

Define the implementation class of the Runnable interface and override the run() method of that interface, whose method body is also the thread execution body of that thread. Create an instance of the Runnable implementation class and use that instance as the target of the Thread to create the Thread object, which is the actual Thread object. Call the start() method of the thread object to start the thread. Custom thread class:

public class MyRunnable implements Runnable {
	@Override
	public void run() {for(inti=0; i<20; i++){ System.out.println(Thread.currentThread().getName()+""+i); }}}Copy the code

The test class:

Public class Demo{public static void main(String[]args){MyRunnable Mr = new MyRunnable(); Thread t = new Thread(Mr,"Small strong");
		t.start();
		for(inti=0; i<20; i++){ System.out.println("Prosperous wealth."+i); }}}Copy the code

3. Difference between Thread and Runnable

Implementing the Runnable interface has advantages over inheriting the Thread class:

Suitable for multiple threads of the same program code to share the same resource.

You can avoid the limitations of single inheritance in Java.

Increased program robustness, decoupled operation, code can be shared by multiple threads, code and thread independent.

Thread pools can only be placed into classes that implement Runable or Callable, not directly into classes that inherit threads.

4. Create multithreading with Lambda expressions

Public Thread004Lambda {public static void main(String[] args) {Thread t = new Thread(()->{ System.out.println("I'm a thread object"); }); t.start(); // Start thread system.out.println ("I'm the main thread"); }}Copy the code

Thread status

1. A thread has the following five states: New Ready: Runnable Running: Running Blocked: Blocked Executed: Dead

The dead state is the last stage in a thread’s life cycle. Threads die for two reasons. One is that the normal thread has done all its work; Another is when a thread is forced to terminate, such as by executing a stop or destroy method to terminate a thread.

2. Terminate the thread

Don’t call the Stop destory method. It’s too violent.

Custom classes:

*/ ** ** */ class MyThread03 implements */ class MyThread03 implements */ class MyThread03 implements Runnable{ private boolean flag =true;

    @Override
    public void run() {
        int i = 0;
        while (true){
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("I'm talking to Amy. I'm talking to Amy."+(i++)+"Words");
            if(! flag){break;
            }
        }
    }
    public void stopThread(){
        flag = false; }}Copy the code

The test class:

public class Thread005 { public static void main(String[] args) throws Exception{ MyThread03 mt = new MyThread03(); Thread t = new Thread(mt); t.start(); Thread.sleep(2000); mt.stopThread(); }}Copy the code

3. Block state (sleep/yield/join methods)

Sleep method: No other thread can access the locked object during sleep. Yield method: Yield CPU usage from running state to ready state. Let the CPU re-select which thread is running. Join method: Wait for the current thread to die. When a thread is waiting for another thread to finish before continuing, the join method of another thread is used. Cause the thread calling the method to finish before it does, that is, wait for the thread calling the method to finish before continuing execution

4. Basic thread information

The default priority for a thread is 5

Thread.MIN_PRIORITY = 1 thread. MAX_PRIORITY = 10 thread. NORM_PRIORITY = 5 Note: A low priority indicates a low probability of obtaining scheduling. It is not always the case that the high-priority thread is called first and the low-priority thread is called later.

Custom classes:

class FatherThread  implements  Runnable {
    @Override
    public void run() {
        System.out.println("Daddy wanted a cigarette and he ran out.");
        System.out.println("Father sent his son to buy a bag of Hongta Mountain."); Thread son = new Thread(new SonThread()); son.start(); // Start a new thread system.out.println ("Father waits for son to buy cigarettes."); try { son.join(); } catch (InterruptedException e) {e.printStackTrace(); } System.out.println("You can smoke now.");
    }
}
class SonThread implements Runnable {
    public void run() {
        System.out.println("Son goes out to buy cigarettes.");
        System.out.println("It takes 10 minutes for my son to buy cigarettes.");
        try {
            for(int i = 1; i <=10; i++) { System.out.println(Thread.currentThread().getName() +"The first" + i + "Minutes");
                Thread.sleep(10);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + "My son came home for cigarettes."); }}Copy the code

The test class:

public class Demo008Thread {
    public static void main(String[] args)throws Exception {

        Thread t1 = new Thread(new SonThread(),"t1");
        Thread t2 = new Thread(new SonThread(),"t2"); // int p = t1.getPriority(); Get priority t1.setPriority(10); // Set thread priority t2.setpriority (1); t1.start(); t2.start(); Thread.sleep(1000); //System.out.println(t.isAlive()); // Check whether the thread is still alive}}Copy the code

Fourth, thread safety

1. Thread synchronization

When we use multiple threads to access the same resource, and multiple threads write to the resource, thread-safety problems tend to occur.

To solve the security problem of multiple threads accessing a resource simultaneously: that is, to solve the problem of duplicate tickets and non-existent tickets, Java provides synchronization to solve the problem.

2. Synchronize code blocks

Synchronized: The synchronized keyword can be used in a block of a method to indicate that only resources in that block are mutually exclusive. Format:

Synchronized {code for synchronized operation}Copy the code

Synchronization locks:

A synchronous lock on an object is just a concept that can be thought of as marking a lock on an object.

The lock object can be of any type. Multiple thread objects use the same lock.

3. Synchronization method

Synchronized methods: Methods that use the synchronized modifier, known as synchronized methods, ensure that thread A executes the method while other threads wait outside the method. Format:


public synchronized void method(){code that may cause thread-safety problems} 1 2Copy the code

Who is the synchronization lock?

For non-static methods, the synchronization lock is this. For static methods, we use the bytecode object (class name.class) of the current method’s class. Integrated cases:

/** * Account */ class Account {String aname; // account name int money; Public Account(String aname, int money) {this.aname = aname; this.money = money; }}Copy the code
class Drawing implements Runnable{ Account account = null; int money = 0; Int acturalMoney = 0; Public Drawing(Account Account, int money) {this. Account = Account; this.money = money; } @Override public voidrun() {synchronized (account){// synchronized (account)if (account.money < money) {
                System.out.println("Insufficient balance, no money to go.");
                return; } try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } account.money -= money; ActuralMoney = money; System.out.println(thread.currentThread ().getName() +"Took" + acturalMoney + "Left"+ account.money); }}}Copy the code

The test class:

*/ Public class Demo010Thread {public static void main(String[] args) throws Exception{// Open an Account account = new Account("Rich and handsome", 100); System.out.println(account.money); Drawing d = new Drawing(account,90); Thread t = new Thread(d,"You" );
        Thread t1 = new Thread(d,"Girlfriend"); t.start(); t1.start(); Thread.sleep(1500); System.out.println(account.money); }}Copy the code

Deadlock is a phenomenon in which two or more processes are blocked during execution because they compete for resources or communicate with each other. Without external action, they cannot proceed. The system is said to be in a deadlock state or a deadlock occurs in the system. These processes that are always waiting for each other are called deadlocked processes.

How to resolve deadlocks:

Often it’s a problem of program logic. Program logic needs to be modified. Try not to hold two object locks at once.