说到线程就不得不说下进程了,大家都知道,许许多多的线程组合在一起就成了一个进程,进程是由操作系统进行资源操作的一个最小的单位,线程则是比进程更小的实际执行操作的单位;每个线程都有自己的堆栈及变量空间。
就好比回家,各种回家线路组成了一个回家的进程,每条线路则代表一个单一的线程
-
继承Thread重写run方法
public class MyThread extends Thread{
private String threadName;
// 控制循环的数量
private int num = 1000;
// 定义商品总数
private int goodsNum = 15;
MyThread(String name) {
this.threadName = name;
}
@Override
public void run() {
for (int i = 0; i< num; i++) {
if (this.goodsNum > 0) {
this.goodsNum -- ;
System.out.println(threadName + "购买了一个,剩余" + this.goodsNum);
}
}
}
public static void main (String[] args) {
MyThread mt = new MyThread("线程1");
MyThread mt1 = new MyThread("线程2");
mt.start();
mt1.start();
}
}
继承Thread需要重写run方法,方法体中就是线程具体的运行逻辑,下面就是代码运行的结果:

有趣的是2个线程都执行了15次,为啥会出现这样的问题?回到代码中
我们是通过new了2个类对象来创建的线程;创建的时候,2个线程都被分配了一样的资源就会导致出现这样 的问题。
?优化如下:
public class MyThread2{
class TestThread extends Thread {
private int goodsNumber = 15;
@Override
public void run() {
for (int i = 0; i <= 16; i++) {
if (this.goodsNumber > 0) {
System.out.println(Thread.currentThread().getName()
+ "购买了一个,剩余:" + (this.goodsNumber --));
}
}
}
}
public static void main(String[] args) throws InterruptedException {
// 开启一个线程任务
TestThread tt = new MyThread2().new TestThread();
// 将任务分配给2个线程去执行
Thread t1 = new Thread(tt,"线程1");
Thread t2 = new Thread(tt,"线程2");
t1.start();
t2.start();
}
}
结果:

备注:直接new一个线程调用run方法并不会创建一个新线程去执行,只是普通对象的方法调用。切记使用start来启动线程
-
实现Runnable接口
根据查看Runnable的源码,Runnable只提供一个run方法,并没有start方法,所以Runnable的启动执行还是需要借助Thread类
public class MyThread3 implements Runnable {
private int num = 5;
@Override
public void run() {
for (int i = 0; i< 10; i++) {
if (this.num > 0) {
System.out.println(Thread.currentThread().getName() + "num left:" + this.num --);
}
}
}
public static void main(String[] args) {
// 创建线程任务
MyThread3 m = new MyThread3();
// 将任务分配给3个线程去执行
new Thread(m,"Thread1").start(); // 线程start后,会放置线程等待队列,等待CPU调度,通过Thread调用run方法
new Thread(m,"Thread2").start();
new Thread(m,"Thread3").start();
}
}
-
Callable和Future的使用
Callable和Runnable有点类似,都是只提供了一个对外接口,不同的是Callable有返回值。
一般Callable搭配ExecutorService来使用;
通过查看源码可以知道ExecutorService可以用来启动Runnable和Callable
// 启动Callable线程
<T> Future<T> submit(Callable<T> task);
// 启动Runnable线程
Future<?> submit(Runnable task);
Future就是对于具体的Runnable或者Callable任务的执行结果进行取消、查询是否完成、获取结果。必要时可以通过get方法获取执行结果,该方法会阻塞直到任务返回结果。
package com.hervey.thread;
import java.util.concurrent.*;
/**
* @program: thread
* @description: Callable线程
* @author: hetangyuese
* @create: 2019-08-26 14:51
**/
public class ThreadCallable {
private int num = 10;
/**
* 实现Callable的线程
*/
class TestCallable implements Callable<String> {
@Override
public String call() throws Exception {
Thread.sleep(5000);
return "hello";
}
}
/**
* 实现Runnable的线程
*/
class TestRunnable implements Runnable {
@Override
public void run() {
int sleepTime = 1000;
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("start");
}
}
public static void main(String[] args) throws ExecutionException,InterruptedException {
// 创建线程池 数量为10
ExecutorService es = Executors.newFixedThreadPool(10);
// Callable线程可以有返回值
Future<String> future = es.submit(new ThreadCallable().new TestCallable());
// 在调用get方法的时候会阻塞线程池知道获取到了才会继续执行
System.out.println(future.get());
try {
// 用于取消线程任务,传参表示是否取消正在执行的线程
future.cancel(true);
if (!future.isCancelled()) {
// 此处通过设置超时时间,在一秒后如果future还未获取到返回值则直接结束
System.out.println(future.get(10000,TimeUnit.MILLISECONDS));
}
} catch (TimeoutException e) {
e.printStackTrace();
}
// isDone方法判断future是否完成即有没有获取到返回值
System.out.println(future.isDone());
// 执行Runnable线程
es.submit(new ThreadCallable().new TestRunnable());
if (!es.isShutdown()) {
es.shutdown();
}
}
}