Han Shunping learned Java in 30 days with zero foundation [Chapter 15 Process Thread]

P580~P599

program

A collection of instructions written in a language to accomplish a specific task.

process

A process is a running program, an execution process of a program, or a running program. It is a dynamic process, with its own process of birth, existence and demise

thread

  1. A thread is created by a process and is an entity of the process
  2. A process can have multiple threads

single thread

Only one thread is allowed to execute at a time

Multithreading

Multiple threads can be executed at the same time

concurrency

At the same time, multiple tasks are executed alternately, creating an illusion of "seemingly simultaneous". Simply put, multitasking achieved by a single-core CPU is concurrency

parallel

At the same time, multiple tasks are executed simultaneously. Multi-core CPU can achieve parallelism

Basic use of threads

There are two ways to use threads in java

  1. Inherit the Thread class, rewrite the run method, Thread01.java
    1. Write a program, start a thread, and output "meow" on the console every second
    2. When the output is 80 times, end the thread
    3. Use JConsole to monitor thread execution
public class Thread01 {
    public static void main(String[] args) throws InterruptedException {
        Cat15 cat = new Cat15();
        cat.start();
        System.out.println("主线程"+Thread.currentThread().getName());
        for (int i = 0; i < 10; i++) {
            System.out.println("主线程"+i);
            Thread.sleep(1000);
        }
    }
}
//一个类继承Thread类,该类就可以当作线程使用
//重写run方法,写自己业务逻辑
//run Thread类实现了Runnable接口的run方法
class Cat15 extends Thread{
    int times = 0;
    @Override
    public void run() {//
        int times =0;
        do {
            System.out.println("miaomiao");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            times++;
        } while (times != 10);
    }
}

  1. Implement the Runnable interface, rewrite the run method, Thread02.java
    1. Java is single-inherited. In some cases, a class may have inherited a parent class. At this time, it is obviously impossible to create a thread by inheriting the Thread class method.
    2. Java designers provide another way to create threads, which is to create threads by implementing the Runnable interface. The bottom layer uses the design pattern [proxy pattern]
    3. Implementing the Runnable interface is more suitable for the situation where multiple threads share a resource, and avoids the limitation of single inheritance
public class Thread02 {
    public static void main(String[] args) {
        Dog15 dog = new Dog15();
        //创建Thread对象,把dog对象 ,放入Thread
        Thread thread = new Thread(dog);
        thread.start();
    }
}
class  Dog15 implements Runnable{
    int count=0;
    @Override
    public void run() {
        while(true){
            System.out.println("wang"+(++count)+Thread.currentThread().getName());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (count==10){
                break;
            }
        }

    }
}
  1. Multithreading, Thread03.java
public class Thread03 {
    public static void main(String[] args) {
        T1 t1 = new T1();
        T2 t2 = new T2();
        Thread thread1 = new Thread(t1);
        Thread thread2 = new Thread(t2);
        thread1.start();
        thread2.start();
    }
}
class T1 implements Runnable{
    int count=0;
    @Override
    public void run() {
        while(true){
            System.out.println("hello1"+(++count));
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (count==10){
                break;
            }
        }
    }
}

class T2 implements Runnable{
    int count=0;
    @Override
    public void run() {
        while(true){
            System.out.println("hello2"+(++count));
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (count==10){
                break;
            }
        }
    }
}

thread terminated

  1. When the thread completes the task, it will automatically exit
  2. The thread can be stopped by using variables to control the exit of the run method

Thread common methods

  1. setName, set the thread name
  2. getName, get the thread name
  3. start, the thread starts to execute, and the bottom layer of the JVM calls the start0 method of the thread
  4. run, call the thread run method
  5. setPriority, set thread priority
  6. getPriority, get thread priority
  7. sleep, specify the number of milliseconds to sleep the current thread
  8. interrupt, interrupt the sleep of the thread
  9. Yield, the courtesy of the thread, yields the cpu to let other threads execute, but the yield time is uncertain, so the yield may not be successful
  10. join, thread jumping, once the jumping thread is successful, it must first execute all the tasks of the inserted thread

User threads and daemon threads

  1. User thread: also called worker thread, when the task of the thread is executed or the notification method ends

  2. Daemon thread: generally serves user threads, when all user threads end, the daemon thread ends automatically

    It is hoped that after the main end, the child thread will end automatically, just set the child thread as a daemon thread

    myDaemonThread.setDaemon(true);

  3. Common Daemon Threads: Garbage Collection Mechanism

thread life cycle

  • NEW
  • RUNNABLE
  • BLOCKED
  • WAITTING
  • TIMED_WAITTING
  • TERMINATED

thread synchronization

  1. In multi-threaded programming, some sensitive data are not allowed to be accessed by multiple threads at the same time. At this time, the synchronous access technology is used to ensure that the data is accessed by at most one thread at any time to ensure the integrity of the data.
  2. It can also be understood: thread synchronization, that is, when a thread is operating on memory, other threads cannot operate on this memory address, until the thread completes the operation, other threads can operate on the memory address

Synchronization method, Synchronized

synchronized(对象){//同步代码块,对象:this,静态方法中:类名.class
  //需要同步的代码
}

public synchronized void m(String name){//同步方法
  //需要同步的代码
}

mutex

  1. In the Java language, the concept of object mutex is introduced to ensure the integrity of shared data operations
  2. Each object corresponds to a tag called a mutex, which is used to ensure that only one thread can access the object at any time
  3. The keyword synchronized is used to associate with the mutex of the object. When an object is modified with synchronized, it indicates that the object can only be accessed by one thread at any time.
  4. The limitation of synchronization: the execution efficiency of the program is reduced
  5. The lock of the non-static synchronization method can be this or other objects (required to be the same object)
  6. The lock of the static synchronization method is the current class itself

Mutex Notes

  1. If the synchronization method is not modified with static, the default lock object: this
  2. If the method uses static modification, the default lock object: current class.class
  3. Implementation steps:
    1. Need to analyze the lock code first
    2. Choose a synchronized code block or a synchronized method
    3. The lock object of multiple threads is required to be the same

thread deadlock

Multiple threads occupy each other's lock resources, but refuse to give in, resulting in deadlocks. Deadlocks should be avoided

release lock

The following operations release the lock

  1. The execution of the synchronization method and synchronization code block of the current thread ends
  2. The current thread encounters a break or return in a synchronous code block or synchronous method
  3. The current thread has an unhandled Error or Exception in the synchronization code block or synchronization method, resulting in an abnormal end
  4. The current thread executes the wait() method of the thread object in the synchronization code block and synchronization method, the current thread pauses and releases the lock

The following operations do not release the lock

  1. When a thread executes a synchronization code block or a synchronization method, the program calls the Thread.sleep() and Thread.yield() methods to suspend the execution of the current thread without releasing the lock
  2. When a thread executes a synchronization code block, other threads call the suspend() method of the thread to suspend the thread, and the thread will not release the lock

Homework for this chapter, Homework1501.java

  1. Start two threads in the main method
  2. The first thread loop randomly prints numbers within 100
  3. until the second thread reads the Q from the keyboard
public class Homework1501 {
    public static void main(String[] args) {
        Th1 th1 = new Th1();
        Th2 th2 = new Th2(th1);
        Thread thread1 = new Thread(th1);
        Thread thread2 = new Thread(th2);
        thread1.start();
        thread2.start();
    }
}

class Th1 implements Runnable{
    private boolean loop =true;
    @Override
    public void run() {
        while(loop){
            System.out.println((int)(Math.random()*100+1));
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    public boolean isLoop() {
        return loop;
    }
    public void setLoop(boolean loop) {
        this.loop = loop;
    }
}
class Th2 implements Runnable {
    private Th1 th1;
    private Scanner scanner = new Scanner(System.in);
    public Th2(Th1 th1) {//构造器中直接传Th1
        this.th1 = th1;
    }
    @Override
    public void run() {
        while (true) {
            System.out.println("请输入");
            char key = scanner.next().toUpperCase().charAt(0);
            if(key=='Q'){
                //以通知方式结束Th1
                th1.setLoop(false);
                break;
            }
        }
    }
}

Homework1502.java

  1. Two users withdraw money from the same card (total 10000)
  2. Withdraw 1000 each time, if the card balance is insufficient, you cannot withdraw
  3. cannot overfetch
public class Homework1502 {
    public static void main(String[] args) {
        T3 a = new T3();
        Thread thread1 = new Thread(a);
        Thread thread2 = new Thread(a);
        thread1.start();
        thread2.start();
    }
}

class T3 implements Runnable {
    static double money = 10000;

    @Override
    public void run() {
        while (true) {
            //synchronized实现线程同步
            //多个线程执行到这里时,就会去争夺this对象
            //谁争夺到this对象锁,就执行synchronized代码块,执行完后,就释放this对象锁
            //争夺不到this对象锁,就blocked,准备继续争夺
            synchronized (this) {
                if (money <= 1000) {
                    System.out.println("余额不足");
                    break;
                }
                money -= 1000;
                System.out.println("余额" + money);
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

Guess you like

Origin blog.csdn.net/weixin_65656674/article/details/126441748