Java并发
一、创建线程的4种方式
概述:1)继承Thread类
2)实现Runnable接口
3)实现Callable接口 后面两种,jdk5后
4)使用线程池
匿名内部类:https://www.cnblogs.com/wuhenzhidu/p/anonymous.html
4大方法:https://www.cnblogs.com/li666/p/11139968.html
继承Thread类
- 创建一个继承于Thread类的子类
- 重写Thread类的run() --> 将此线程执行的操作声明在run()中
- 创建Thread类的子类的对象
- 通过此对象调用start():①启动当前线程 ② 调用当前线程的run()
/**
* 创建线程的4种方式:1、继承Thread
* 2、实现Runnable
* 3、实现Callable,搭配FutureTask
* 4、构建线程池
*
*
*
*
* 方式一:继承Thread类
*
* 两个注意点:
* 1、我们启动一个线程,必须调用start(),不能调用run()的方式启动线程。
* 2、如果再启动一个线程,必须重新创建一个Thread子类的对象,调用此对象的start()。
*
*
*
* @author sgstar
* @create 2020-11-17 15:31
*/
// 这个例子是启用一个新的类,去继承Thread,
public class MyThread {
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName() + ":" + "输出的结果");
ThreadDemo1 threadDemo1 = new ThreadDemo1();
threadDemo1.setName("demo1");
threadDemo1.start();
}
}
class ThreadDemo1 extends Thread {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + ":" + "输出的结果");
}
}
// 这个例子,是直接使用主类继承Thread,创建多线程。并且从输出结果来看,并不是线程调用了start()方法,它就先执行。
// 然后我们可以使用sleep,说句晚安,再看看结果。
/*
public class MyThread extends Thread {
public static void main(String[] args) {
// 创建一个新线程
MyThread threadDemo1 = new MyThread();
// 设置线程的名称
threadDemo1.setName("demo1");
// 开启线程
threadDemo1.start();
// try {
// sleep(1);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
System.out.println(Thread.currentThread().getName() + ":" + "输出的结果");
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + ":" + "输出的结果");
}
} */
// 3、匿名内部类:1、匿名子类(继承父类) 2、实现接口的匿名类
//public class MyThread {
// public static void main(String[] args) {
//
// new Thread() {
// @Override
// public void run() {
// System.out.println(Thread.currentThread().getName() + ":" + "输出的结果");
// }
// }.start();
//
//
// //new到.start();这直接,整部分的内容表示Thread类的子类对象,
// // 然后.start就会调用run()方法,start就把线程给开启,然后调用run()方法
//
// System.out.println(Thread.currentThread().getName() + ":" + "输出的结果");
// }
//
//}
两个注意点: 1、我们启动一个线程,必须调用start(),不能调用run()的方式启动线程。
2、如果再启动一个线程,必须重新创建一个Thread子类的对象,调用此对象的start()。
实现Runnable接口
- 创建一个实现了Runnable接口的类
- 实现类去实现Runnable中的抽象方法:run()
- 创建实现类的对象
- 将此对象作为参数传递到Thread类的构造器中,创建Thread类的对象
- 通过Thread类的对象调用start()
匿名内部类:https://www.cnblogs.com/wuhenzhidu/p/anonymous.html
1、匿名子类(继承父类) 2、实现接口的匿名类
/**
* 方式二:实现Runnable接口
* @author sgstar
* @create 2020-11-17 16:41
*/
// 1、这个例子是启用一个新的类,去实现Runnable,
public class MyRunnable {
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName() + ":" + "输出的结果");
ThreadDemo2 threadDemo2 = new ThreadDemo2();
Thread t1 = new Thread(threadDemo2);
t1.setName("demo2");
t1.start();
}
}
class ThreadDemo2 implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + ":" + "输出的结果");
}
}
// 2、这个例子,是直接使用主类实现Runnable,创建多线程。
//public class MyRunnable implements Runnable{
// public static void main(String[] args) {
//
// System.out.println(Thread.currentThread().getName() + ":" + "输出的结果");
//
// MyRunnable threadDemo2 = new MyRunnable();
// Thread t1 = new Thread(threadDemo2);
// t1.setName("demo2");
// t1.start();
//
// }
//
// @Override
// public void run() {
// System.out.println(Thread.currentThread().getName() + ":" + "输出的结果");
// }
//}
// 3、匿名内部类
// lambda express
// 2.1 口诀
// 拷贝小括号,写死右箭头,落地大括号
//public class MyRunnable {
// public static void main(String[] args) {
//
// System.out.println(Thread.currentThread().getName() + ":" + "输出的结果");
//
// new Thread(new Runnable() {
// @Override
// public void run() {
// System.out.println(Thread.currentThread().getName() + ":" + "输出的结果");
// }
// },"SunG").start();
//
// new Thread(() -> {
// System.out.println(Thread.currentThread().getName() + ":" + "输出的结果");
// },"new").start();
// }
//}
实现Callable接口
- 创建一个类并实现Callable接口
- 重写call()方法,将所要完成的任务的代码写进call()方法中,需要注意的是call()方法有返回值,并且可以抛出异常
- 如果想要获取运行该线程后的返回值,需要创建Future接口的实现类的对象,即FutureTask类的对象,调用该对象的get()方法可获取call()方法的返回值
- 使用Thread类的有参构造器创建对象,将FutureTask类的对象当做参数传进去,然后调用start()方法开启并运行该线程。
/**
*
* 这像认识一个不认识的同学,我可以找中间人介绍。中间人是什么?java多态,一个类可以实现多个接口!!
* FutureTask<Integer> ft = new FutureTask<Integer>(new MyThread());
* new Thread(ft, "AA").start();
* 运行成功后如何获得返回值?ft.get();
*
* FutureTask的get方法需要放在,最后使用,因为如果放在中间的话,主线程会等待,返回值返回了之后才执行
*
*
* 面试题:Callable接口与Runnable接口的区别?
*
* 答: (1)是否有返回值
* (2)是否抛异常
* (3)落地方法不一样,一个是run,一个是call
*
*
* @author sgstar
* @create 2020-11-17 18:40
*/
// 1、这个例子是启用一个新的类,去实现Callable,
public class MyCallable {
public static void main(String[] args) throws ExecutionException, InterruptedException {
System.out.println(Thread.currentThread().getName() + ":" + "输出的结果");
ThreadDemo3 threadDemo3 = new ThreadDemo3();
FutureTask<Integer> futureTask = new FutureTask(threadDemo3);
Thread t1 = new Thread(futureTask);
t1.setName("demo3");
t1.start();
System.out.println(futureTask.get());
}
}
class ThreadDemo3 implements Callable {
@Override
public Integer call() throws Exception {
System.out.println(Thread.currentThread().getName() + ":" + "输出的结果");
return 1988;
}
}
// 2、这个例子,是直接使用主类实现Callable,创建多线程。,
//public class MyCallable implements Callable{
// public static void main(String[] args) throws ExecutionException, InterruptedException {
//
// System.out.println(Thread.currentThread().getName() + ":" + "输出的结果");
//
// MyCallable threadDemo3 = new MyCallable();
// FutureTask<Integer> futureTask = new FutureTask(threadDemo3);
// Thread t1 = new Thread(futureTask);
// t1.setName("demo3");
// t1.start();
// System.out.println(futureTask.get());
//
// }
//
// @Override
// public Object call() throws Exception {
// System.out.println(Thread.currentThread().getName() + ":" + "输出的结果");
// return 1988;
// }
//}
// 3、匿名内部类,不好用。取不到,返回值。
使用线程池
-
使用Executors类中的newFixedThreadPool(int num)方法创建一个线程数量为num的线程池
-
调用线程池中的execute()方法执行由实现Runnable接口创建的线程;调用submit()方法执行由实现Callable接口创建的线程
-
调用线程池中的shutdown()方法关闭线程池
MyThreadPool我自己的,多家实例总和
/**
* 方式四:使用线程池
*
* 使用线程池技术,
* ExecutorService,
* Executors工具类创建线程池,三种方式,这里列举一种
* execute()方法用于实现Runnable接口创建的线程
* submit()方法适用于实现Callable接口创建的线程
*
*
*
*
* @author sgstar
* @create 2020-11-17 19:12
*/
// 1、这个例子是启用新的类,去使用ThreadPool,
public class MyThreadPool {
public static void main(String[] args) throws ExecutionException, InterruptedException {
System.out.println(Thread.currentThread().getName() + ":" + "输出的结果");
// 通过线程池工厂创建线程数量为5的线程池
ExecutorService executorService = Executors.newFixedThreadPool(5);
// 执行线程,execute()适用于实现Runnable接口创建的线程
executorService.execute(new ThreadRunnableDemo5());
// 执行线程,submit()适用于实现Callable接口创建的线程
ThreadCallableDemo6 threadCallableDemo6 = new ThreadCallableDemo6();
Future<Integer> future = executorService.submit(threadCallableDemo6);
// 获取call()方法的返回值
System.out.println(future.get());
// 关闭线程池
executorService.shutdown();
}
}
class ThreadRunnableDemo5 implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + ":" + "输出的结果Runnable");
}
}
class ThreadCallableDemo6 implements Callable {
@Override
public Integer call() {
System.out.println(Thread.currentThread().getName() + ":" + "输出的结果Callable");
return 1988;
}
}
// 这个方法不行,在使用submit出现了错误,舍弃
//public class MyThreadPool implements Runnable,Callable{
//
// public static void main(String[] args) throws ExecutionException, InterruptedException {
//
// System.out.println(Thread.currentThread().getName() + ":" + "输出的结果");
// // 通过线程池工厂创建线程数量为5的线程池
// ExecutorService executorService = Executors.newFixedThreadPool(5);
// // 执行线程,execute()适用于实现Runnable接口创建的线程
// executorService.execute(new MyThreadPool());
// // submit()适用于实现Callable接口创建的线程
// MyThreadPool myThreadPool = new MyThreadPool();
// Future<Integer> future = executorService.submit(myThreadPool);
// // 获取call()方法的返回值
// System.out.println(future.get());
// // 关闭线程池
// executorService.shutdown();
// }
//
// @Override
// public void run() {
// System.out.println(Thread.currentThread().getName() + ":" + "输出的结果Runnable");
// }
//
// @Override
// public Integer call() throws Exception {
// System.out.println(Thread.currentThread().getName() + ":" + "输出的结果Callable");
// return 1988;
// }
//}
//3、这个例子是使用匿名内部类,但是不能获取返回值
//public class MyThreadPool {
//
// public static void main(String[] args) {
//
// System.out.println(Thread.currentThread().getName() + ":" + "输出的结果");
// ExecutorService executorService = Executors.newFixedThreadPool(2);
// executorService.execute(new Runnable() {
// @Override
// public void run() {
// System.out.println(Thread.currentThread().getName() + ":" + "输出的结果Runnable");
// }
// });
//
// executorService.submit(new Callable() {
// @Override
// public Integer call() {
// System.out.println(Thread.currentThread().getName() + ":" + "输出的结果Callable");
// return 1988;
// }
// });
// executorService.shutdown();
// }
//}
周阳老师的,线程池该用哪个?更加全面,汇总,介绍线程池的总的方法。这里简单介绍线程池方法
/**
* 1.继承Thread
* 2.实现Runnable
* 3.实现Callable,搭配FutureTask
* 4.使用线程池技术,ExecutorService,Executors工具类,execute()方法,submit()方法
* java提供了,3种不同的创建线程池的方法,但是三种不同的方法实际上可以汇总成一个方法
* ThreadPoolExecutor(),这里面一共有7大参数
*
*
* @author sgstar
* @create 2020-11-17 21:38
*/
public class MyThreadPoolDemo {
public static void main(String[] args) {
// ExecutorService threadPool = Executors.newFixedThreadPool(5);// 一个池子5个工作线程
// ExecutorService threadPool = Executors.newSingleThreadExecutor();// 一个池子1个工作线程
// ExecutorService threadPool = Executors.newCachedThreadPool();//一个池子N个工作线程
// try {
// for (int i = 1; i <= 10; i++) {
// threadPool.execute(() -> {
// System.out.println(Thread.currentThread().getName() + "\t办理业务");
// });
// // 睡1秒钟,延时
// try { TimeUnit.SECONDS.sleep(1); } catch (Exception e) { e.printStackTrace(); }
// }
// } catch (Exception e) {
// e.printStackTrace();
// } finally {
// threadPool.shutdown();
// }
System.out.println(Runtime.getRuntime().availableProcessors()); // 内核数
ExecutorService threadPool = new ThreadPoolExecutor(
2,
5, // 内核数+1 +2
2L,
TimeUnit.SECONDS,
new LinkedBlockingQueue<>(3),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.CallerRunsPolicy());
try {
for (int i = 0; i < 10; i++) {
threadPool.execute(() -> {
System.out.println(Thread.currentThread().getName() + "\t办理业务");
// try { TimeUnit.SECONDS.sleep(1); } catch (Exception e) { e.printStackTrace(); }
});
}
} catch (Exception e) {
e.printStackTrace();
} finally {
threadPool.shutdown();
}
}
--------------------------------------四种创建线程方法对比--------------------------------------
实现Runnable和实现Callable接口的方式基本相同,不过是后者执行call()方法有返回值,后者线程执行体run()方法无返回值,因此可以把这两种方式归为一种这种方式与继承Thread类的方法之间的差别如下:
1、线程只是实现Runnable或实现Callable接口,还可以继承其他类。
2、这种方式下,多个线程可以共享一个target对象,非常适合多线程处理同一份资源的情形。
3、但是编程稍微复杂,如果需要访问当前线程,必须调用Thread.currentThread()方法。
4、继承Thread类的线程类不能再继承其他父类(Java单继承决定)。
5、前三种的线程如果创建关闭频繁会消耗系统资源影响性能,而使用线程池可以不用线程的时候放回线程池,用的时候再从线程池取,项目开发中主要使用线程池
注:在前三种中一般推荐采用实现接口的方式来创建多线程
Thread和Runnable的实质是继承关系,没有可比性。无论使用Runnable还是Thread,都会new Thread,然后执行run方法。用法上,如果有复杂的线程操作需求,那就选择继承Thread,如果只是简单的执行一个任务,那就实现runnable。
其实,前面三种方法,到最后都需要NEW THREAD(),有人说创建线程这3个都算一种方法。也可以,但是,我觉得面试的时候,面试官应该更加倾向于4种这样的回答。
那么工作中用哪个创建线程池的方法呢?一个都不用,用自定义的。
参考:https://blog.csdn.net/longshengguoji/article/details/41126119
https://www.cnblogs.com/li666/p/11139968.html