深入理解Java多线程—如何创建多线程

目录

一、继承Thread类

二、实现Runnable接口

三、实现Callable接口

四、使用线程池

4.1 使用Executors(不推荐)  

4.2 使用ThreadPoolExecutor(推荐)


一、继承Thread类

/**
 * 
 */
package com.createThread;

/**
 * 创建线程(不推荐):继承Thread类
 * @author yyx
 * 2021年3月3日
 */
public class CreateThread {
	public static void main(String[] args) {
		// 线程类
		InheritThread inheritThread = new InheritThread();
		// 设置线程名称
		inheritThread.setName("线程一");
		inheritThread.start();

		// 主线程
		Thread.currentThread().setName("主线程");
		for (int i = 1; i <= 20; i++) {
			System.out.println(Thread.currentThread().getName() + ":" + i);
		}
	}
}

class InheritThread extends Thread {

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

}

二、实现Runnable接口

/**
 * 
 */
package com.createThread;

/**
 * 创建线程(推荐):实现Runnable接口
 * @author yyx
 * 2021年3月3日
 */
public class CreateThread {
	public static void main(String[] args) {
		// 实现Runnable接口
		ImplementRunnable implementRunnable = new ImplementRunnable();
		Thread thread = new Thread(implementRunnable);
		thread.setName("线程二");
		thread.start();

		// 主线程
		Thread.currentThread().setName("主线程");
		for (int i = 1; i <= 20; i++) {
			System.out.println(Thread.currentThread().getName() + ":" + i);
		}
	}
}

class ImplementRunnable implements Runnable {

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

}

三、实现Callable接口

/**
 * 
 */
package com.createThread;

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

/**
 * 创建线程(根据要求选择):实现Callable接口
 * @author yyx
 * 2021年3月3日
 */
public class CreateThread {
	public static void main(String[] args) {
		ImplementCallable implementCallable = new ImplementCallable();
		FutureTask<Integer> task = new FutureTask<Integer>(implementCallable);
		Thread thread = new Thread(task, "有返回值的线程");
		thread.start();

		Thread.currentThread().setName("主线程");
		for (int i = 1; i <= 20; i++) {
			System.out.println(Thread.currentThread().getName() + ":" + i);
		}

		try {
			System.out.println(task.get());
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}

class ImplementCallable implements Callable<Integer> {

	@Override
	public Integer call() {
		Integer total = 0;
		try {
			for (int i = 1; i <= 50; i++) {
				total += i;
			}
			return total;
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return null;
	}
}

四、使用线程池

       4.1 使用Executors(不推荐)  

package com.createThread;

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

/**
 * 1.newFixedThreadPool和newSingleThreadExecutor,队列数量弹性,
 *   创建的线程的队列最大值为INTEGER.max容易造成OOM
 * 2.newCachedThreadPool和newScheduledThreadPool,线程数量弹性,
 *   创建的线程数量最大值为INTEGER.max容易造成OOM
 * @author yyx
 * 2021年3月3日
 */
public class CreateThread {
	public static void main(String[] args) {
		newSingleThreadExecutor();
	}

	/**
	 * 创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程
	 * 这种类型的线程池特点是:
	 * 1.缓存型池子,先查看池中有没有以前建立的线程,如果有,就reuse,如果没有,就建立一个新的线程加入池中
	 * 2.缓存型池子,通常用于执行一些生存周期很短的异步型任务;因此一些面向连接的daemon型server中用得不多
	 * 3.能reuse的线程,必须是timeout IDLE内的池中线程,缺省timeout是60s,超过这个IDLE时长,线程实例将被终止及移出池
	 * 4.注意,放入CachedThreadPool的线程不必担心其结束,超过TIMEOUT不活动,其会自动被终止
	 */
	public static void newCachedThreadPool() {
		ExecutorService executorService = Executors.newCachedThreadPool();
		for (int i = 1; i <= 10; i++) {
			final int index = i;
			executorService.execute(new Runnable() {

				@Override
				public void run() {
					System.out.println(Thread.currentThread().getName() + "当前运行到:" + index);
					try {
						Thread.sleep(3000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			});
		}

		executorService.shutdown();
	}

	/**
	 * 创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待
	 * 这种类型的线程池特点是:
	 * 1.newFixedThreadPool与cacheThreadPool差不多,也是能reuse就用,但不能随时建新的线程
	 * 2.其独特之处:任意时间点,最多只能有固定数目的活动线程存在,此时如果有新的线程要建立,只能放在另外的队列中等待,
	 *   直到当前的线程中某个线程终止直接被移出池子
	 * 3.和cacheThreadPool不同,FixedThreadPool没有IDLE机制,所以FixedThreadPool多数针对一些很
	 *   稳定很固定的正规并发线程,多用于服务器       
	 * 4.从方法的源代码看,cache池和fixed 池调用的是同一个底层池,只不过参数不同:fixed池线程数固定,并且是0秒
	 *   IDLE(无IDLE)cache池线程数支持0-Integer.MAX_VALUE(显然完全没考虑主机的资源承受能力),60秒IDLE 
	 */
	public static void newFixedThreadPool() {
		ExecutorService executorService = Executors.newFixedThreadPool(3);
		for (int i = 1; i <= 10; i++) {
			final int index = i;
			executorService.execute(new Runnable() {

				@Override
				public void run() {
					System.out.println(Thread.currentThread().getName() + "当前运行到:" + index);
					try {
						Thread.sleep(3000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			});
		}
		executorService.shutdown();
	}

	/**
	 * newScheduledThreadPool创建一个定长线程池,支持定时及周期性任务执行
	 * 这种类型的线程池特点是:
	 * 1.调度型线程池
	 * 2.这个池子里的线程可以按schedule依次delay执行,或周期执行
	 */
	public static void newScheduledThreadPool() {
		ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(5);
		scheduledExecutorService.schedule(new Runnable() {

			@Override
			public void run() {
				System.out.println("延迟3秒执行");
			}
		}, 3, TimeUnit.SECONDS);

		scheduledExecutorService.scheduleAtFixedRate(new Runnable() {

			@Override
			public void run() {
				System.out.println("延迟3秒后每1秒执行一次");

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

		scheduledExecutorService.shutdown();
	}

	/**
	 * newSingleThreadExecutor创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,
	 * 保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行
	 * 这种类型的线程池特点是:
	 * 1.单例线程,任意时间池中只能有一个线程
	 * 2.用的是和cache池和fixed池相同的底层池,但线程数目是1-1,0秒IDLE(无IDLE)
	 */
	public static void newSingleThreadExecutor() {
		ExecutorService executorService = Executors.newSingleThreadExecutor();
		for (int i = 1; i <= 10; i++) {
			final int index = i;
			executorService.execute(new Runnable() {

				@Override
				public void run() {
					System.out.println(Thread.currentThread().getName() + "当前运行到:" + index);
					try {
						Thread.sleep(3000);
					} catch (Exception ex) {
						ex.printStackTrace();
					}
				}
			});
		}

		executorService.shutdown();
	}
}

       4.2 使用ThreadPoolExecutor(推荐)

package com.createThread;

import java.io.Serializable;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 
 * @author yyx
 * 2021年3月3日
 */
public class CreateThread {
	public static void main(String[] args) {
		newThreadPoolExecutor();
	}

	public static void newThreadPoolExecutor() {
		long currentTimeMillis = System.currentTimeMillis();

		ThreadPoolExecutor threadPool = new ThreadPoolExecutor(5, 6, 3, TimeUnit.SECONDS,
				new ArrayBlockingQueue<Runnable>(3));

		for (int i = 1; i <= 10; i++) {
			try {
				String task = "task=" + i;
				System.out.println("创建任务并提交到线程池中:" + task);
				threadPool.execute(new ThreadPoolTask(task));

				Thread.sleep(100);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		try {
			// 等待所有线程执行完毕当前任务。
			threadPool.shutdown();

			boolean loop = true;
			do {
				// 等待所有线程执行完毕当前任务结束
				loop = !threadPool.awaitTermination(2, TimeUnit.SECONDS);// 等待2秒
			} while (loop);

			if (loop != true) {
				System.out.println("所有线程执行完毕");
			}

		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			System.out.println("耗时:" + (System.currentTimeMillis() - currentTimeMillis));
		}
	}
}

class ThreadPoolTask implements Runnable, Serializable {
	private static final long serialVersionUID = 1L;

	private Object attachData;

	ThreadPoolTask(Object tasks) {
		this.attachData = tasks;
	}

	public void run() {
		try {
			System.out.println("开始执行任务:" + attachData + "任务,使用的线程池,线程名称:" + Thread.currentThread().getName());
			System.out.println();
		} catch (Exception e) {
			e.printStackTrace();
		}
		attachData = null;
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值