进程和线程
进程和线程都是一个时间段的描述,是CPU工作时间段的描述,不过是颗粒大小不同。
![56e92c25e2e89480c4bf2e7d1d932574.png](https://i-blog.csdnimg.cn/blog_migrate/b65dfa897c93c9bcc6336877c941c4cc.jpeg)
他们主要区别是:进程不共享内存,线程可以共享内存。
线程:
- CPU中的Thread:
CPU中的线程,我们也叫它们Thread,和OS中的线程的名字一样。他们和cpu相关,常说的4核心8线程就是指cpu线程。CPU的Thread就那么固定几个,是稀缺资源。 - 操作系统中的Thread: 操作系统中的进程可以很多,进程中的线程就更多了。软件操作系统调度的基本单位是OS的Thread。我们开发中所指的就是这个线程。
Thread和Runnable
Java中线程的创建有两种方式: 1.通过继承Thread类,重写Thread的run()方法,将线程运行的逻辑放在其中。
2.通过实现Runnable接口,实例化Thread类。
我们通常使用第二种,因为可以复用Runnable,更容易实现资源共享,能多个线程同时处理一个资源。
// 1public class MyRunnable implements Runnable { @Override public void run() { System.out.println("this is a Runnable"); }}// 2public class MyThread extends Thread { @Override public void run() { super.run(); System.out.println("this is thread"); }}// 具体使用public class Main { public static void main(String[] args) { // 第一种 Thread thread1 = new Thread(new MyRunnable()); thread1.start(); // 第二种 MyThread thread2 = new MyThread(); thread2.start(); }}
而实际Android开发工作中,以上两种都不用,我们通常使用Android提供的Handler和java.util包里的Executor。
Executor
Executor 是一个接口,execute执行Runnable。
public interface Executor { /** * Executes the given command at some time in the future. The command * may execute in a new thread, in a pooled thread, or in the calling * thread, at the discretion of the {@code Executor} implementation. * * @param command the runnable task * @throws RejectedExecutionException if this task cannot be * accepted for execution * @throws NullPointerException if command is null */ void execute(Runnable command);}
看下使用:
val executor: Executor = Executors.newCachedThreadPool() executor.execute { }
点进去newCachedThreadPool,发现返回的是一个ExecutorService。ExecutorService就是Executor的实现了。
return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue()); }
ExecutorService
ExecutorService有两个方法:
void shutdown(); 是指不再添加任务,执行完已有任务后结束。 List shutdownNow(); 是立即调用线程的interrupt()结束所有的线程。
ThreadPoolExecutor
上面看到Executors里面new的是ThreadPoolExecutor,我们看下ThreadPoolExecutor的构造方法:
//五个参数的构造函数public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue workQueue)//六个参数的构造函数-1public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue workQueue, ThreadFactory threadFactory)//六个参数的构造函数-2public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue workQueue, RejectedExecutionHandler handler)//七个参数的构造函数public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue workQueue, ThreadFactory threadFactory, RejectedExe