Thread method and thread lock

1. Five states of threads

New: a new thread object is created
Runnable: when the start method is called, the thread is in an executable state.
Running: the executable thread object obtains the time slice of the cpu and is scheduled by the cpu for execution.
Blocked: the thread gives up the right to use the cpu for some reason and temporarily stops running.
Dead: the thread finishes running or exits the run method due to an exception and stops running.

Note: the blocking state cannot be changed to the executable state. You can only restore the executable state and wait for cpu deployment again

2. Common methods of thread

1. yeild method (comity)

public class MethodVip implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"Running...");
    }

    public static void main(String[] args) {
        Method method = new Method();
        MethodVip methodVip = new MethodVip();

        new Thread(methodVip, "Page").start();
        new Thread(method,"George").start();
    }
}

class Method implements Runnable{

    @Override
    public void run() {
        Thread.yield();
        System.out.println(Thread.currentThread().getName()+"Running...");

    }
}

Two different classes are respectively implemented to implement the Runable interface, then the run method is rewritten, the yeild method is used in one of the run methods, and the start method of the two threads is invoked to open two threads. It is found many times that threads using the yeild method generally execute later, but sometimes execute first. It can be seen that comity is not necessarily successful, and the cpu scheduler can ignore the comity request of the thread.

2. join method (queue jumping)

public class MethodVip implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            try {
                Thread.sleep(100);
                System.out.println(Thread.currentThread().getName()+"Running...");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        MethodVip methodVip = new MethodVip();

        Thread p1 = new Thread(methodVip, "Page");

        p1.start();
        p1.join();

        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName()+"Running...");
        }

    }
}

The thread using the join method will block the main thread. The main thread can execute only after its own execution is completed.
3. Sleep method (sleep) and wait method
The sleep method makes the thread sleep, and the wait method makes the thread wait. The difference is that the sleep method does not release the lock, while the wait method releases the lock. Wait is the method of Object class and sleep is the method of Thead class.

3. Wire program lock

1,synchronized

public class SynchronizeTest {

    public static void main(String[] args) {
        Bank bank = new Bank("bank for economic construction", 100);
        Person boy = new Person(bank, 50, "boy");
        Person girl = new Person(bank, 80, "girl");

        boy.start();
        girl.start();
    }
}

class Bank {
    private String name;
    public int money;

    public Bank(String name,int money) {
        this.name = name;
        this.money = money;
    }
}

class Person extends Thread{
    Bank bank;
    private int myMonmey;
    private int takeMoney;

    public Person(Bank bank,int takeMoney,String name){
        super(name);
        this.bank=bank;
        this.takeMoney=takeMoney;

    }
    @Override
    public void run() {
        synchronized (bank){
            if (bank.money-takeMoney<=0){
                System.out.println(Thread.currentThread().getName()+"My account is out of money");
                return;
            }

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            myMonmey=myMonmey+takeMoney;
            System.out.println(this.getName()+"Yes"+myMonmey);

            bank.money=bank.money-takeMoney;
            System.out.println("The bank has money left"+bank.money);
        }
    }
}

This is to simulate the operation of two people withdrawing money from the bank at the same time. Because sleep simulates the delay, two people will enter the bank to withdraw money at the same time. When they see 100 yuan, they can operate on the 100 yuan. After the operation, they exit, which may have a negative value. Theoretically, there is only one resource, so there will be two resources by default. Therefore, we must lock resources. Synchronized locks this object by default. We use synchronized code blocks to lock the bank object, so that the money in the bank can only be operated by another person after one person completes the operation.
2,lock

import java.util.concurrent.locks.ReentrantLock;

public class LockTest1{

    public static void main(String[] args) {
        Lock2 lock2 = new Lock2();
        new Thread(lock2,"cattle").start();
        new Thread(lock2,"student").start();
        new Thread(lock2,"teacher").start();
    }
}

class Lock2 implements Runnable{

    private int ticket=10;
    boolean flag = true;
    ReentrantLock lock = new ReentrantLock();
    @Override
    public void run() {
        while(ticket>2){
            try{
                lock.lock();
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName()+"Bought the first one" + ticket--+"ticket");

            }finally {
                lock.unlock();
            }
        }
    }
}

Lock is a display lock, which needs to be locked by lock method and unlocked by unlock method. synchronized lock is an implicit lock and does not need to be declared.

Keywords: Java Back-end

Added by jonno946 on Wed, 05 Jan 2022 23:18:53 +0200