进程和线程
线程创建三种方式:
- 1.继承Thread类
- 2.实现Rnnable接口
- 3.实现Callable接口
- 继承Thread
public class thread extends Thread{ @Override public void run() { for (int i = 0; i < 20; i++) { System.out.println("这是run线程"+i); } } public static void main(String[] args) { // 开启run线程 start 是同时运行 run方法是先执行run方法 在执行主线程 thread thread = new thread(); thread.start();// 开启线程 for (int i = 0; i < 200; i++) { System.out.println("这是main线程"+i); } } }
-
实现Rnnable接口
public class runnable implements Runnable{ @Override public void run() { for (int i = 0; i < 20; i++) { System.out.println("这是run线程"+i); } } public static void main(String[] args) { runnable runnable = new runnable();// 创建线程对象 new Thread(runnable,"定义线程名").start();// 需要一个Thread对象 for (int i = 0; i < 200; i++) { System.out.println("这是main线程"+i); } } }
-
实现Callable接口
public class callable implements Callable<Object> { @Override public Object call() throws Exception { Object object = new Object(); return object; } public static void main(String[] args) throws ExecutionException, InterruptedException { // 创建线程 callable callable = new callable(); // 创建执行服务 ExecutorService pool = Executors.newFixedThreadPool(3); // 执行线程 获取结果 Future<Object> res = pool.submit(callable); Object obj = res.get(); // 关闭服务 pool.shutdownNow(); } }
~ run方法和start方法两者是有区别的,run会先运行run里代码在运行主线程,start是同时运行。
~ 线程开启并不一定立即执行,是由cpu调度的,人为无法干预。
~ 获取当前线程的名字
Thread.currentThread().getName();
~ 获取线程的状态
State state = thread.getState();
线程的五种状态
- 初始状态 new当创建了一个线程时,会进入此状态。
- 就绪状态 当初始状态调用了start()方法时,会进入此状态。
- 运行状态 当就绪状态的线程获得cpu时间片,即调度到它,进入运行状态。
- 堵塞状态 当调用sleep,wait方法或同步锁定,线程进入堵塞,代码不往下执行,堵塞事件结束后重新进入就绪状态,等待cpu调度。
- 终止状态 线程中断或者执行完所有代码,进入终止状态。
synchronized 隐式锁
synchronize有两种时用,同步方法,同步代码块。synchronize同步方法默认锁的时this,即当前对象,同步代码块可以锁任何对象。死锁线程双方锁了对方所需要的临界资源,导致双方都处于堵塞状态。
同步代码块:
synchronized (obj){//obj 需要锁的对象
}
lock 显示锁
不同于synchronize(修饰符),lock是可重入锁,是一个对象,他只能锁代码块,由jdk1.5推出的新特性,lock已自身为标记,代替了临界资源互斥锁标记。
创建lock锁:
private final ReentrantLock lock = new ReentrantLock(); // 创建lock锁对象
try{
lock.lock(); // 加锁
...
}finally{
lock.unlock(); // 解锁
}
线程之间的通信
wait():当临界资源调用wait()方法时 当前线程 放弃时间片 放弃互斥锁标记 进入等待区(进入阻塞状态)
notify():当临界资源调用notify()时会根据一定策略 唤醒等待区中的某个线程 该线程重新回归就绪状态
notifyAll():当临界资源调用notifyAll()时 唤醒等待区中的所有线程 所有线程进入就绪状态
sleep()和wait()区别
- 它俩来自不同的类,sleep()是Thread类的,wait()是来自于Object类。
- sleep() 只让出了CPU,却不会释放对象锁,处于堵塞状态,它需要设置休眠时间。wait()会放弃对象锁,并让出cpu资源,处于等待状态,使用notify()和notifyAll()来唤醒。
- sleep() 会抛出InterruptedException异常,需要进行相关处理,而wait()不需要捕获异常。
线程安全的集合
线程池
~ 顾名思义,一个池子用来装线程的容器,可已设定线程分配数量上限,将预先创建线程对象存入池中,并重用线程池中的线程。
~ 好处是减少创建和销毁线程的次数。
线程池的基本接口:Executor
线程池接口:ExecutorService
线程池工具类:Executors,用于创建线程。
- newSingleThreadPool 创建一个单线程的线程池。这个线程池只有一个线程在工作,也就是相当于单线程串行执行所有任务。如果这个唯一的线程因为异常结束,那么会有一个新的线程来替代它, 此线程池保证所有任务的执行顺序按照任务的提交顺序执行。
public class ThreadPoolExecutorTest { public static void main(String[] args) { ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor(); for (int i = 0; i < 10; i++) { final int index = i; singleThreadExecutor.execute(new Runnable() { public void run() { try { System.out.println(index); Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } }); } } }
- newFixedThreadPool 创建固定大小的线程池。每次提交一个任务就创建一个线程,直到线程达到线程池的最大大小。某个线程因为执行异常而结束,那么线程池会补充一个新线程。
public class ThreadPoolExecutorTest { public static void main(String[] args) { ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3); for (int i = 0; i < 10; i++) { final int index = i; fixedThreadPool.execute(new Runnable() { public void run() { try { System.out.println(index); Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } }); } } }
- newCachedThreadPool 创建一个可缓存的线程池。如果线程池的大小超过了处理任务所需要的线程,那么就会回收部分变量(60秒不执行任务)的线程,当任务数增加时,此线程池又可以智能的添加新线程来处理任务。此线程池不会对线程池大小做限制,线程池大小完全依赖于操作系统(或者说JVM)能够创建的最大线程大小。
public class ThreadPoolExecutorTest { public static void main(String[] args) { ExecutorService cachedThreadPool = Executors.newCachedThreadPool(); for (int i = 0; i < 10; i++) { final int index = i; try { Thread.sleep(index * 1000); } catch (InterruptedException e) { e.printStackTrace(); } cachedThreadPool.execute(new Runnable() { public void run() { System.out.println(index); } }); } } }
- newScheduledThreadPool 创建一个定长的线程池,而且支持定时的以及周期性的任务执行,支持定时及周期性任务执行。
public class ThreadPoolExecutorTest { public static void main(String[] args) { ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5); scheduledThreadPool.schedule(new Runnable() { public void run() { System.out.println("delay 3 seconds"); } }, 3, TimeUnit.SECONDS); } }
-
使用
public static void main(String[] args) { //创建线程任务对象 MyRunnable02 mr=new MyRunnable02(); //获取线程池对象 ExecutorService es=Executors.newFixedThreadPool(2); //调用方法执行线程任务 es.submit(mr); es.submit(mr); //销毁线程池 es.shutdown(); }
-
Lambda方式
private static final ExecutorService pool = Executors.newFixedThreadPool(10); @Test public void test1() { pool.execute(() ->{ }); }