search
HomeJavaJavaBaseHow to implement java multithreading
How to implement java multithreadingDec 04, 2019 am 11:06 AM
java

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
带你搞懂Java结构化数据处理开源库SPL带你搞懂Java结构化数据处理开源库SPLMay 24, 2022 pm 01:34 PM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于结构化数据处理开源库SPL的相关问题,下面就一起来看一下java下理想的结构化数据处理类库,希望对大家有帮助。

Java集合框架之PriorityQueue优先级队列Java集合框架之PriorityQueue优先级队列Jun 09, 2022 am 11:47 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于PriorityQueue优先级队列的相关知识,Java集合框架中提供了PriorityQueue和PriorityBlockingQueue两种类型的优先级队列,PriorityQueue是线程不安全的,PriorityBlockingQueue是线程安全的,下面一起来看一下,希望对大家有帮助。

完全掌握Java锁(图文解析)完全掌握Java锁(图文解析)Jun 14, 2022 am 11:47 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于java锁的相关问题,包括了独占锁、悲观锁、乐观锁、共享锁等等内容,下面一起来看一下,希望对大家有帮助。

一起聊聊Java多线程之线程安全问题一起聊聊Java多线程之线程安全问题Apr 21, 2022 pm 06:17 PM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于多线程的相关问题,包括了线程安装、线程加锁与线程不安全的原因、线程安全的标准类等等内容,希望对大家有帮助。

Java基础归纳之枚举Java基础归纳之枚举May 26, 2022 am 11:50 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于枚举的相关问题,包括了枚举的基本操作、集合类对枚举的支持等等内容,下面一起来看一下,希望对大家有帮助。

详细解析Java的this和super关键字详细解析Java的this和super关键字Apr 30, 2022 am 09:00 AM

本篇文章给大家带来了关于Java的相关知识,其中主要介绍了关于关键字中this和super的相关问题,以及他们的一些区别,下面一起来看一下,希望对大家有帮助。

Java数据结构之AVL树详解Java数据结构之AVL树详解Jun 01, 2022 am 11:39 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于平衡二叉树(AVL树)的相关知识,AVL树本质上是带了平衡功能的二叉查找树,下面一起来看一下,希望对大家有帮助。

一文掌握Java8新特性Stream流的概念和使用一文掌握Java8新特性Stream流的概念和使用Jun 23, 2022 pm 12:03 PM

本篇文章给大家带来了关于Java的相关知识,其中主要整理了Stream流的概念和使用的相关问题,包括了Stream流的概念、Stream流的获取、Stream流的常用方法等等内容,下面一起来看一下,希望对大家有帮助。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.