How to create multiple threads in Java

The relationship between process and thread

A process is a collection of all threads, and each thread is an execution path in the process.

What is a process and what is a thread

Process, every program running on the system is a process.

Thread, a thread is a set of instructions, or a special section of a program, which can be executed independently in the program, and each process contains one or more threads.

The benefits of multithreading (analogous to the concept of synchronization and asynchronous)

☞ Improve the efficiency of task execution

☞ Threads (tasks) do not affect each other, if one thread hangs, the other will run as usual

Three ways to create threads in Java

1. Inherit the Thread class

☞ Create inherited class InheritThread and override run() method

public class InheritThread extends Thread {

    @Override
    public void run() {
        System.out.println("run()方法被执行...");
    }
}

☞ Create the main thread class ThreadDemo, call the inherited class in the main() method

 

public class ThreadDemo {

    public static void main(String[] args) {
        System.out.println("创建新线程...");
        InheritThread inheritThread = new InheritThread();
        inheritThread.start();  //启动一个线程是调用start()方法,而不是直接调用run()方法
        System.out.println("新线程已启动...");
        System.out.println("main()方法启动...");
    }
}

result:

 

ps: Calling the run() method directly to run is equivalent to still in the main thread instead of restarting a new thread; the execution sequence of multithreading is cross-execution , although the above results can not see the effect of cross-execution, but when the thread When the number of executions is large enough (such as loops), the effect of cross execution can be reflected.

2. Implement Runnable interface ( recommended )

Create an implementation class ImplementRunnable that implements the Runnable interface

public class ImplementRunnable implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 100; i++){
            System.out.println("run()==>"+i);
        }
    }
}

Main thread

ImplementRunnable implementRunnable = new ImplementRunnable();
System.out.println("创建新线程...");
Thread thread = new Thread(implementRunnable);  //传入对象,无法直接调用start()方法
thread.start();
System.out.println("新线程已启动...");
System.out.println("main()方法启动...");
for (int i = 0; i < 100; i++){
    System.out.println("main()==>"+i);
}

ps: Inheriting Thread has the same function as implementing interface Runnable, but it is recommended to use the method of implementing interfaces, because interfaces can be implemented in multiples, and inheritance can only be single inheritance.

3. Use anonymous inner classes

No need to create other classes, just create an anonymous inner class in the main thread

System.out.println("创建新线程...");
new Thread(new Runnable() {
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("run()==>" + i);
        }
    }
}).start();
System.out.println("新线程创建成功...");
for (int i = 0; i < 100; i++){
    System.out.println("main()==>"+i);
}

commonly used ways

1、sleep()

☞ Let the current thread change from running state to sleeping state, if the sleeping time is up, it will return to running state (using delay can clearly see the effect of cross execution);

☞ Cannot release the lock

@Override
public void run() {
    for (int i = 0; i < 10; i++){
        try {  //在run()方法中不能抛出异常,只能捕获异常
            Thread.sleep(1000);  //延时1秒
        } catch (InterruptedException e) {
        }
        System.out.println("i="+i);
    }
}

2. Set the name of the thread

public class TestThread extends Thread {//只有使用继承的方式才能使用getId()方法和getName()方法

    @Override
    public void run() {
        for (int i = 0; i < 10; i++){
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
            }
            System.out.println("线程ID:"+getId()+"  线程名称:"+getName()+" ==>>i="+i);
        }
    }
}
public static void main(String[] args) {
    TestThread thread = new TestThread();
    thread.setName("线程1");
    thread.start();
    TestThread thread2 = new TestThread();
    thread2.setName("线程2");
    thread2.start();
}

Use the way to implement the interface

public class TestThread2 implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 10; i++){
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
            }
            Thread thread = Thread.currentThread();  //获取当前线程,才能调用具体的设置方法
            System.out.println("线程ID:"+thread.getId()+"  线程名称:"+thread.getName()+" ==>>i="+i);
        }
    }
}
TestThread2 testThread2 = new TestThread2();
Thread thread = new Thread(testThread2);
thread.start();

Same effect as above 

3. Use of join() method

☞ Increase the priority and wait until the thread is executed before executing other threads

public static void main(String[] args) {
        Thread threadJoin = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 60; i++) {
                    System.out.println("子线程i: " + i);
                }
            }
        });
        threadJoin.start();
        try {
            threadJoin.join();  //提高子线程的优先级
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        for (int i = 0; i < 30; i++) {
            System.out.println("主线程: "+i);
        }
        System.out.println("主线程执行完毕...");
    }

☞ Effect

Multi-threaded running status (5 types)

New state==》Ready state==》Running state==》Hibernation state==》Death state

New state: created, but did not call the start() method

Ready state: call the start () method, waiting for the CPU scheduling

Running status: After the CPU allocates resources and executes the run() method

Sleep state: call sleep() or wait() method, after sleep, it will return to ready state and continue to wait for CPU scheduling

Death state: after the execution of the run() method is completed or the stop() method is manually called [ generally, the stop() method is not called ]

// 2019/04/14 update

Daemon thread

☞ The difference between a daemon thread and a user thread is that the daemon thread will be destroyed with the destruction of the main thread

public static void main(String[] args) {

    Thread t1 = new Thread(new Runnable() {
        @Override
        public void run() {
            for (int i = 0; i < 30; i++) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("子线程i: " + i);
            }
        }
    });
    t1.setDaemon(true);  //设置为守护线程,和主线程一起销毁
    t1.start();
    for (int j = 0; j < 5; j++){
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("主线程j: "+j);
    }
    System.out.println("主线程执行完毕...");
}

☞ Effect

 

Guess you like

Origin blog.csdn.net/ip_JL/article/details/88597139