一起学JAVA之【基础篇】多线程实现
基本概念
并发:同一时间间隔执行两个或两个以上的任务
并行:同一时刻执行两个或两个以上的任务
同一时间间隔理解为同一时间段内(两个任务再不同时间执行,由于间隔时间很短,导致宏观上是同时) 同一时刻理解为同时
进程:资源分配的最小单位,可以由一个或者多个线程组成
线程:cpu调度的最小单位
线程状态:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-GOhzYuXs-1635317661786)(D:\code\java\文档\markdown\图片\20190208203341726.png)]
Java线程实现的4种方式
###### 1、继承Thread类型,重载run 方法
class MyThread extends Thread{
public void run(){
//执行自己的业务
System.out.println("this is my thread")
}
}
class ThreadTest{
public static void main(String[] args){
MyThread mythread = new MyThread();
mythread.start();//启动线程
}
}
缺点:Java是单继承,当MyThread类需要继承其他类时就不能通过这种方式创建线程了
2、实现Runnable接口
class MyThread implements Runnable{
public void run(){
System.out.println("this is my runnable thread");
}
}
class ThreadTest{
public static void main(String[] args){
Thread thread = new Thread(new MyThread());
thread.start();//启动线程
Thread thread1 = new Thread(() -> System.out.println("this is my runnable thread"));//lambda表达式实现
thread1.start();
}
}
底层都是调的Thread中init() 方法,只是这种传了一个Runnable 的 target
3、实现Callable配合FutureTask
class ThreadTest{
public static void main(String[] args){
Callable<String> callable = new Callable<String>() {
@Override
public String call() throws Exception {
Thread.sleep(1000);
return "this is call";
}
};
//future 请求返回阻塞
FutureTask<String> oneTask = new FutureTask<String>(callable);
Thread callableThread = new Thread(oneTask);
callableThread.start();
String callRes = oneTask.get();
System.out.println(callRes);
}
}
优点:可以知道线程执行结束状态,但是是阻塞的,线程结束前都不会进行下一步操作
4、线程池(推荐使用)
class MyThread implements Runnable{
public void run(){
System.out.println("this is my runnable thread");
}
}
class ThreadTest{
//thread pool
ExecutorService pool = Executors.newFixedThreadPool(10);//10 是线程数量
pool.execute(new MyThread());
}
rService pool = Executors.newFixedThreadPool(10);//10 是线程数量
pool.execute(new MyThread());
}
优点:配置一个线程池,每次需要用到的时候都从线程池中去拿,减少资源消耗