Java Advanced Multithreading (1)

1. Multithreading

1. Inherit the Thread class (method 1)

1) Implement multi-threading

Inherit the Thread class,
override the run() method,
create a thread object , and
call the start() method to start

Calling the run method will be executed as a normal method, and only calling the start method will start a new thread for execution.

2) Advantages and disadvantages

  • advantage

Coding is simple

  • shortcoming

It is a single inheritance. After the thread class inherits Thread, it cannot inherit other classes, which is not easy to extend.

2. Implement the Runnable interface (method 2)

1) Implement multi-threading

Define a thread task class MyRunnable to implement the Runnable interface, rewrite the run() method,
create a MyRunnable object
, hand over the MyRunnable task object to the Thread thread object for processing
, call the start() method of the thread object to start the thread

2) Implement multi-threading (anonymous inner class method)

Create an anonymous inner class object of Runnable and
hand it over to Thread for processing
Call start() of the thread object to start the thread

3) Advantages and disadvantages

  • advantage

Implements the Runnale interface and can continue to inherit and implement

  • shortcoming

The thread has execution result and cannot return directly

3. Implement Callable and FutureTask interfaces (method 3)

1) Implement multi-threading

Create the Callable interface implementation class, rewrite the call() method, and encapsulate
the Callable object into a thread task object with FutureTask. The
thread task object is handed over to Thread for processing, and the start() method is called to start the thread.
After the execution of the task is completed, the get method to get the result of the task execution

2) Advantages and disadvantages

  • advantage

The thread task class only implements the interface, and can continue to inherit the class and implement the interface, which is highly extensible.
You can get the result of the thread execution after the thread is executed.

  • shortcoming

Coding is complicated

method name explain
public FutureTask<>(Callable call) Encapsulate the Callable object into a FutureTask object
public V get() throws Exception Get the result returned by the thread executing the call method

4. Thread thread

1) Constructor of Thread

Constructor explain
public Thread(String name) Specify a name for the current thread
public Thread(Runnable target) Encapsulate a Runnable object into a thread object
public Thread(Runnable target ,String name ) Encapsulate the Runnable object into a thread object and specify the thread name

insert image description here

public class MyRunnable implements Runnable{
    
    
    @Override
    public void run() {
    
    
        for (int i = 0; i < 10; i++) {
    
    
            System.out.println("Runnable "+Thread.currentThread().getName()+" ===>> "+i);
        }
    }
}

public class ClassStructure {
    
    
    public static void main(String[] args){
    
    
        MyRunnable myRunnable = new MyRunnable();
        //分配一个带有指定目标新的线程对象
        Thread thread = new Thread(myRunnable);
        //获取当前线程名称
        String name = thread.getName();
        System.out.println("当前名称-1:"+name);
        //设置新的名称
        thread.setName("Thread-1-新");
        String newName = thread.getName();
        System.out.println("当前名称-1:"+ newName);
        //启动多线程
        thread.start();

        MyRunnable mr = new MyRunnable();
        //分配一个带有指定目标新的线程对象并指定名称
        Thread td = new Thread(mr,"指定名称:");
        String strName = td.getName();
        System.out.println("当前名称-2:"+ strName);
        td.start();
    }
}

5. Thread method

1) Thread gets and sets the thread name

method name explain
String getName​() Get the name of the current thread, the default thread name is Thread-index
void setName​(String name) Change the name of this thread to the specified name, the thread name can also be set through the constructor

insert image description here

public class ClassStructure {
    
    
    public static void main(String[] args){
    
    
        Thread thread = new Thread();
        String name = thread.getName();
        System.out.println(name);

        thread.setName("线程1");
        String nameNew = thread.getName();
        System.out.println(nameNew);
    }
}


2) The Thread class gets the object of the current thread

method name explain
public static Thread currentThread() Returns a reference to the currently executing thread object

Notice:

1. This method is a static method of the Thread class and can be called directly using the Thread class.
2. Which thread object is obtained when this method is called in which thread execution.

public class MyThread extends Thread {
    
    
    public MyThread(String name) {
    
    
        super(name);
    }

    @Override
    public void run() {
    
    
        super.run();
        for (int i = 0; i < 10; i++) {
    
    
            //获得当前正在执行的线程对象
            Thread td = Thread.currentThread();
            //获取当前线程名称
            System.out.println(td.getName() + i);
        }
    }
}

3) The thread sleep method of the Thread class:

method name explain
public static void sleep(long time) Let the current thread sleep for the specified time before continuing to execute, in milliseconds

insert image description here

public class MyThread extends Thread {
    
    
    public MyThread(String name) {
    
    
        super(name);
    }

    @Override
    public void run() {
    
    
        super.run();
        for (int i = 0; i < 10; i++) {
    
    
            //获得当前正在执行的线程对象
            Thread td = Thread.currentThread();
            //获取当前线程名称
            System.out.println(td.getName() + i);

        }
    }
}

public class ClassStructure {
    
    
    public static void main(String[] args) throws InterruptedException {
    
    
        MyRunnable mr = new MyRunnable();
        //分配一个带有指定目标新的线程对象并指定名称
        Thread td = new Thread(mr,"指定名称:");
        String strName = td.getName();
        System.out.println("当前名称-2:"+ strName);
        System.out.println(System.currentTimeMillis());
        //暂停3秒
        Thread.sleep(3000);
        System.out.println(System.currentTimeMillis());
        td.start();
    }
}


2. Thread Safety

Multiple threads access the same shared resource at the same time and modify the resource

3. Thread synchronization

  • concept

Fix thread safety issues

  • Guaranteed thread safety

Multiple threads can access shared resources successively, which can solve security problems

  • Thought

Locking: Allowing multiple threads to access shared resources in turn can solve security problems

1. Synchronized code block

  • principle

Only one thread can enter at a time. After the execution is completed, it is automatically unlocked, and other threads can enter and execute.

  • effect

The core code of thread safety issues is locked

  • achieve thread safety

The core code in question is to use synchronized to lock,
and only one thread can occupy the lock and enter into execution at a time.

  • Format
synchronized(同步锁对象) {
    
    
	操作共享资源的代码(核心代码)
}
  • Synchronization lock object requirements

For instance methods, it is recommended to use this as the lock object.
For static methods, it is recommended to use the bytecode (class name.class) object as the lock object

2. Synchronization method

  • principle

Only one thread can enter at a time. After the execution is completed, it is automatically unlocked, and other threads can enter and execute.

  • effect

The core code of thread safety issues is locked

  • Format
  • achieve thread safety

The core code in question is to use synchronized to lock,
and only one thread can occupy the lock and enter into execution at a time.

修饰符 synchronized 返回值类型 方法名称(形参列表) {
    
    
	操作共享资源的代码
}
  • Synchronization lock object requirements

For instance methods, it is recommended to use this as the lock object.
For static methods, it is recommended to use the bytecode (class name.class) object as the lock object

  • underlying principle

If the method is an instance method: The synchronized method uses this as the lock object by default. But the code should be highly object-oriented.
If the method is a static method: the synchronization method uses the class name .class as the lock object by default.

3. Lock

  • principle

The lock object Lock is more flexible and convenient to use.
Lock implementation provides a wider range of locking operations than using synchronized methods and statements.
Lock is an interface that cannot be directly instantiated. Here, its implementation class ReentrantLock is used to build a Lock lock object

method name explain
public ReentrantLock​() Get the implementation class object of the Lock lock
void lock() lock
void unlock() unlock

Guess you like

Origin blog.csdn.net/walykyy/article/details/126708333