5 minutes to learn three kinds of Java to create multithreaded approach

Java There are three basic ways to create threaded tasks

Method 1: Thread class inheritance

We can inherit the Thread class and override the run () method to create a new thread task.

// 继承 Thread 类
class MyThread extends Thread {
    private String name;
    
    public MyThread(String name) {
        this.name = name;
    }

	// 重写 run() 方法,任务代码放在这里
	@Override
    public void run() {
    	// 任务:报数
        for(int i = 0; i < 3; i++) {
            System.out.println(name + ": " + i);
        }
	}
}

public class Main {
    public static void main(String[] args) {
    	// 实例化 Thread 类,调用 start() 方法开启新线程
        MyThread t1 = new MyThread("线程1");
        MyThread t2 = new MyThread("线程2");
        t1.start();
        t2.start();
    }
}

Please note that we have () method can only be opened by the new thread Start , open a new thread runs automatically run () method.

If we call here is the run () method, then we just were created in the current thread running run () method only, there will be no new thread.

Program output:

线程1: 0
线程2: 0
线程2: 1
线程2: 2
线程1: 1
线程1: 2

We look closely, you will find that thread 1 and thread 2 is a cross-operating, if we re-run a program, you will get different results, because attempts to seize CPU resources between threads, which thread can grab CPU resources It is completely random.

However, even if the thread 1 and thread 2 running order is random, but logical thread within itself is still in order.

Method 2: implement Runnable

We can also create a class and implement Runnable, and then pass the class constructor Thread class.

// 实现 Runnable 接口
class MyRunnable implements Runnable {
    private String name;

    public MyRunnable(String name) {
        this.name = name;
    }

	// 重写 run() 方法,任务代码放这里
    @Override
    public void run() {
        for (int i = 0; i < 3; i++) {
            System.out.println(name + ": " + i);
        }
    }  
}

public class Main {
    public static void main(String[] args) {
    	// 实例化 Runnable 对象,并传递给 Thread 类
        MyRunnable runnable1 = new MyRunnable("线程1");
        MyRunnable runnable2 = new MyRunnable("线程2");
        Thread t1 = new Thread(runnable1);
        Thread t2 = new Thread(runnable2);
        t1.start();
        t2.start();
    }
}

Method 3: Use a thread pool (recommended)

Use the thread pool to create a thread is the recommended way to compare, because the thread pool can control the number of threads, threads and reuse, saving the overhead of creating a new thread.

Executors through method calls, we can create a thread pool.

If a new task, thread pool idle threads will be put to use. If there is no idle thread, the new task will be placed in the waiting queue, wait for the next free thread.

Using Executors of newFixedThreadPool () creates the specified number of threads, and by calling the execute () method to perform the task.

public class Main {
    public static void main(String[] args) {
    	// 在线程池里预先创建4个线程
        ExecutorService executor = Executors.newFixedThreadPool(4);
        // 调用 execute() 方法传递任务给线程池里的线程
        executor.execute(new MyRunnable("线程1"));
        executor.execute(new MyRunnable("线程2"));
        // 需要显示地关闭线程池,否则线程池将持续等待下一个任务
        executor.shutdown();
    }
}

class MyRunnable implements Runnable {
    private String name;

    public MyRunnable(String name) {
        this.name = name;
    }

    @Override
    public void run() {
        for (int i = 0; i < 3; i++) {
            System.out.println(name + ": " + i);
        }
    }  
}

Please note that we need to call the shutdown () method to explicitly close the thread pool, or the thread pool will continue to wait for the next task.

Executors also provide different kinds of thread pools:

  • newCachedThreadPool()
  • newSingleThreadExecutor ()

Here do not describe details, please refer to the official document:

Oracle Java thread pool of official documents

Published 14 original articles · won praise 8 · views 2196

Guess you like

Origin blog.csdn.net/vandavidchou/article/details/103814010