java中直接或间接创建线程的方法总结

在java开发中,经常会涉及多线程的编码,那么通过直接或间接创建线程的方法有哪些?现整理如下:

1、继承Thread类,重写run()方法

class Worker extends Thread {

	@Override
	public void run() {
		System.out.println("Code run in a sub thread!");
	}
}

public class CreateThreadTester {

	public static void main(String[] args) throws InterruptedException {
		Thread t = new Worker();
		t.start();
		t.join();
	}

}

2、实现Runnable接口,重写run()

class Worker implements Runnable {

	@Override
	public void run() {
		System.out.println("Code run in a sub thread!");
	}
}

public class CreateThreadTester {

	public static void main(String[] args) throws InterruptedException {
		Runnable task = new Worker();
		Thread t = new Thread(task);
		t.start();
		t.join();
	}

}

3、实现Callable接口,重写call()

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

class Worker implements Callable<Integer> {

	@Override
	public Integer call() {
		System.out.println("Code run in a sub thread!");
		return Integer.valueOf(10);
	}
}

public class CreateThreadTester {

	public static void main(String[] args) throws InterruptedException, ExecutionException {
		Callable<Integer> thread = new Worker();
		FutureTask<Integer> task = new FutureTask<Integer>(thread);
		Thread t = new Thread(task);
		t.start();
		System.out.println("Thread return value:" + task.get());
	}

}

4、使用定时器

(1)基于类java.util.Timer和重写TimerTask的run()执行定时任务

     示例代码如下:

import java.util.Timer;
import java.util.TimerTask;

class Worker extends TimerTask {

	@Override
	public void run() {
		System.out.println("Code run in a sub thread!");
	}

}

public class CreateThreadTester {

	public static void main(String[] args) {
		Timer timer = new Timer();
		TimerTask task = new Worker();
		timer.schedule(task, 0);
	}

}

(2) 基于java.util.concurrent.Executors.newSingleThreadScheduledExecutor()执行定时任务

     示例代码如下:

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ThreadScheduledExecutorTester01 {

	private static ThreadLocal<SimpleDateFormat> dateFormat = new ThreadLocal<SimpleDateFormat>() {
		public SimpleDateFormat initialValue() {
			return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		}
	};

	public static void main(String[] args) {

		ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
		service.schedule(new Runnable() {

			@Override
			public void run() {
				System.out.println(dateFormat.get().format(new Date()) + " -- 11111111111111");

			}
		}, 2, TimeUnit.SECONDS);

		service.schedule(new Runnable() {

			@Override
			public void run() {
				System.out.println(dateFormat.get().format(new Date()) + " -- 22222222222222222222");

			}
		}, 2, TimeUnit.SECONDS);

		service.scheduleAtFixedRate(new Runnable() {

			@Override
			public void run() {
				System.out.println(dateFormat.get().format(new Date()) + " -- 3333333333333333333333");

			}
		}, 1, 5, TimeUnit.SECONDS);

	}

}

5、使用java.util.concurrent.Executors工厂类

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

class Worker implements Runnable {

	@Override
	public void run() {
		System.out.println("Code run in a sub thread!");
	}

}

public class CreateThreadTester {

	public static void main(String[] args) {
		ExecutorService service = Executors.newSingleThreadExecutor();
		Runnable command = new Worker();
		service.execute(command);
	}

}

Executors 的工具类可以创建三种类型的普通线程池:

  • 固定大小的线程池:Executors.newFixedThreadPool(n)
  • 单线程池:Executors.newSingleThreadExecutor()
  • 缓存线程池:Executors.newCachedThreadPool()

     当提交任务速度高于线程池中任务处理速度时,缓存线程池会不断的创建线程。 适用于提交短期的异步小程序,以及负载较轻的服务器,而负载相对较重的服务器应使用固定大小的线程池。

6、Spring中使用@EnableAsync和@Async注解

在pom.xml文件中配置spring-boot-starter依赖:

		<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
			<version>2.2.1.RELEASE</version>
		</dependency>

示例代码如下:

import java.util.concurrent.Executor;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

@Service
class AsyncService {

	@Async
	public void testAsync_1() {
		System.out.println("testAsync_1 is running, thread :" + Thread.currentThread().getName());
	}

	@Async
	public void testAsync_2() {
		System.out.println("testAsync_2 is running, thread :" + Thread.currentThread().getName());
	}
}

@Configuration
@ComponentScan("com.tang.spring")
@EnableAsync
class Config implements AsyncConfigurer {

	public Executor getAsyncExecutor() {
		ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
		taskExecutor.setCorePoolSize(2);
		taskExecutor.setMaxPoolSize(2);
		taskExecutor.setQueueCapacity(2);
		taskExecutor.initialize();
		return taskExecutor;
	}
}

public class SpringApplicationTester {

	public static void main(String[] args) {
		AbstractApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
		AsyncService bean = context.getBean(AsyncService.class);
		bean.testAsync_1();
		bean.testAsync_2();
	}

}

7、其他方式待整理中

略。。。。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值