Home >Java >JavaBase >How to implement java multithreading

How to implement java multithreading

尚
Original
2019-12-04 11:06:593797browse

How to implement java multithreading

How to implement multi-threading in java: (Recommended: java video tutorial)

Method 1: Inheriting the Thread class

1. Create a subclass that inherits from the Thread class

2. Rewrite run() in the Thread class: declare the operation to be performed by this thread in run()

3. Create an object of a subclass of Thread

4. Call start() of this object: ① Start the thread ② Call the run() method of the current thread

Method 2: How to implement the Runnable interface

1. Create a class that implements the Runnable interface

2. Implement the abstract method in the Runnable interface: run(): will create The operations to be performed by the thread are declared in this method

3. Create an object of the Runnable interface implementation class

4. Pass this object as a parameter to the constructor of the Thread class to create the Thread class Object

5. Call start() in the Thread class: ① Start the thread ② Call the run() of the thread --->Call run() of the Runnable interface implementation class

The following The two methods are new in jdk1.5!

Method 3: Implement the Callable interface

Instructions:

1. Compared with using Runnable, Callable is more powerful

2. Compared with the run() method, the implemented call() method can return values

3. The method can throw exceptions

4. Supports generic return values

5. You need to use the FutureTask class, such as obtaining the return results.

The Future interface can cancel the execution results of specific Runnable and Callable tasks, query whether it is completed, obtain the results, etc. FutureTask is the only implementation class of the Future interface. FutureTask also implements the Runnable and Future interfaces. It can be executed by a thread as a Runnable, and can also be used as a Future to get the return value of the Callable

Method 4: Use the thread pool

Instructions:

Create multiple threads in advance, put them into the thread pool, obtain them directly when using them, and put them back into the pool after use. It can avoid frequent creation and destruction and realize reuse. Similar to public transportation in life.

Benefits:

1. Improve response speed (reduce the time to create new threads)

2. Reduce resource consumption (reuse threads in the thread pool, no need to Created every time)

3. Facilitate thread management

Example:

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.ThreadPoolExecutor;

//方式一
class ThreadTest extends Thread {
	@Override
	public void run() {
		for (int i = 0; i < 10; i++) {
			System.out.println(Thread.currentThread().getName() + ":" + i);
		}
	}
}

// 方式二
class RunnableTest implements Runnable {
	@Override
	public void run() {
		for (int i = 0; i < 10; i++) {
			System.out.println(Thread.currentThread().getName() + ":" + i);
		}
	}
}

// 方式三
class CallableTest implements Callable<Integer> {

	@Override
	public Integer call() throws Exception {
		int sum = 0;
		for (int i = 0; i < 10; i++) {
			System.out.println(Thread.currentThread().getName() + ":" + i);
			sum += i;
		}
		return sum;
	}

}

// 方式四
class ThreadPool implements Runnable {

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

}

public class Test {
	public static void main(String[] args) {
		// 继承Thread
		ThreadTest thread = new ThreadTest();
		thread.setName("方式一");
		thread.start();

		// 实现Runnable
		RunnableTest runnableTest = new RunnableTest();
		Thread thread2 = new Thread(runnableTest, "方式二");
		thread2.start();

		// 实现Callable<> 有返回值
		CallableTest callableTest = new CallableTest();
		FutureTask<Integer> futureTask = new FutureTask<>(callableTest);
		new Thread(futureTask, "方式三").start();
		// 返回值
		try {
			Integer integer = futureTask.get();
			System.out.println("返回值(sum):" + integer);
		} catch (Exception e) {
			e.printStackTrace();
		}

		// 线程池
		ExecutorService pool = Executors.newFixedThreadPool(10);

		ThreadPoolExecutor executor = (ThreadPoolExecutor) pool;
		/*
		 * 可以做一些操作:
		 * corePoolSize:核心池的大小 
		 * maximumPoolSize:最大线程数
		 * keepAliveTime:线程没任务时最多保持多长时间后会终止
		 */
		executor.setCorePoolSize(5);

		// 开启线程
		executor.execute(new ThreadPool());
		executor.execute(new ThreadPool());
		executor.execute(new ThreadPool());
		executor.execute(new ThreadPool());

	}

}

For more java knowledge, please pay attention to the java basic tutorial column.

The above is the detailed content of How to implement java multithreading. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn