Java多线程并发编程

饭宝  论坛元老 | 2022-9-16 17:15:03 | 显示全部楼层 | 阅读模式
打印 上一主题 下一主题

主题 1003|帖子 1003|积分 3009

多线程并发

在多核CPU中,利用多线程并发编程,可以更加充分地利用每个核的资源
在Java中,一个应用程序对应着一个JVM实例(也有地方称为JVM进程),如果程序没有主动创建线程,则只会创建一个主线程。但这不代表JVM中只有一个线程,JVM实例在创建的时候,同时会创建很多其他的线程(比如垃圾收集器线程)。
线程创建

线程有三种创建方式:

  • 继承Thread类 (可以说是 将任务和线程合并在一起)
  • 实现Runnable接口 (可以说是 将任务和线程分开了)
  • 实现Callable接口 (利用FutureTask执行任务)
对比:Runnable接口解决了Thread单继承的局限性。而Callable解决了Runnable无法抛异常给调用方的局限性。
  1. class T extends Thread {
  2.     @Override
  3.     public void run() {
  4.         println("我是继承Thread的任务");
  5.     }
  6. }
  7. class R implements Runnable {  //解决了单继承问题
  8.     @Override
  9.     public void run() {
  10.         println("我是实现Runnable的任务");
  11.     }
  12. }
  13. class C implements Callable<String> {
  14.     @Override
  15.     public String call() throws Exception {  //可以抛异常
  16.         println("我是实现Callable的任务");
  17.         return "success";    //任务有返回值
  18.     }
  19. }
复制代码
线程启动


  • 调用线程的start()方法,这里要注意,只有Thread方法可以调用start(),因此需要为其他类型的线程创建方式实例分配Thread实例。
  1. // 启动继承Thread类的任务
  2. Thread MyThread = new MyThread();
  3. MyThread.start();
  4. class MyThread extends Thread {
  5.     @Override
  6.     public void run() {
  7.         System.out.println("hello myThread" + Thread.currentThread().getName());
  8.     }
  9. }
  10. // 启动实现Runnable接口的任务
  11. MyRunnable myRunnable = new MyRunnable();
  12. Thread thread = new Thread(myRunnable);  //要给实现Runnable的实例分配新的对象
  13. thread.start();
  14. class MyRunnable implements Runnable{
  15.     @Override
  16.     public void run(){
  17.         System.out.println("hello myRunnable" + Thread.currentThread().getName());
  18.     }
  19. }
  20. // 启动实现了Callable接口的任务 结合FutureTask 可以获取线程执行的结果
  21. FutureTask<String> target = new FutureTask<>(new C());  //C是实现了Callable接口的类
  22. new Thread(target).start();
  23. log.info(target.get());
复制代码
各线程类图


常用方法

方法说明setName("String");给线程设置名称getName();获取线程的名称Thread.currentThread();获取当前执行的线程对象Thread.sleep(ms);线程休眠(以ms为单位)线程同步

多个线程同时操作某个临界资源可能出现业务安全问题。采用互斥访问
加锁:把临界资源进行上锁,每次只允许一个线程进入访问完成后才解锁,允许其他进程进入
同步代码块

对代码块上锁
快捷键:CTRL+ALT+T
关于锁对象的选择
最好不要用任意唯一的锁对象,因为这会影响其他无关线程的执行。
规范上:建议使用临界资源作为锁对象
对于实例方法建议使用this作为锁对象
对于静态方法建议使用字节码(类名.class)作为锁对象
  1. synchronized(同步锁对象) {  //synchronized(this) 只锁自己的临界资源
  2.         //操作系统资源的代码(出现安全问题的核心代码)
  3. }
复制代码
同步方法

对方法上锁
在方法定义时加上synchronized关键字即可
同步方法底层有隐式锁对象
如果方法是实例方法:同步方法默认使用this作为锁对象
如果方法是静态方法:同步方法默认使用类名.class作为锁对象
  1. 修饰符 synchronized 返回值类型 方法名称(形参列表) {
  2.         //操作系统资源的代码
  3. }
复制代码
Lock锁
  1. //创建锁
  2. private final Lock lock = new ReentranLock();
  3. lock.lock();    //加锁
  4.         try {
  5.         //锁住的内容
  6.     } finally {
  7.                 lock.unlock();  //解锁
  8.     }
复制代码
线程通信

典型应用:生产者-消费者模型
实现方法:使用一个共享变量实现线程通信
方法名称功能锁.wait()让当前线程等待并释放所占锁,直到另一个线程调用notify()方法或notifyAll()方法锁.notify()唤醒正在等待的单个线程锁.notifyAll()唤醒正在等待的所有线程线程池

一个可以复用线程的技术,当请求过多时用于降低系统开销
ExecutorService代表线程池接口
如何得到线程池对象

方式一:使用ExecutorService的实现类ThreadPoolExecutor创建线程池对象



创建临时线程的条件:①核心线程全忙        ②任务队列满
拒绝任务的条件:临时线程和核心线程全忙
线程池处理Runnable任务的方法:
  1. public class Communication {
  2.     public static void main(String[] args) {
  3.         //线程池创建
  4.         ExecutorService pool = new ThreadPoolExecutor(3,5,2, TimeUnit.MINUTES, new ArrayBlockingQueue<>(5),new ThreadPoolExecutor.AbortPolicy());
  5.         Runnable myRunnable = new myRunnable();
  6.                 //线程池产生Runnable线程对象
  7.         pool.execute(myRunnable);
  8.         pool.execute(myRunnable);
  9.         pool.execute(myRunnable);
  10.         pool.execute(myRunnable);
  11.         pool.execute(myRunnable);
  12.         pool.execute(myRunnable);
  13.         pool.execute(myRunnable);
  14.         pool.execute(myRunnable);
  15.         //开始创建临时线程
  16.         pool.execute(myRunnable);
  17.         pool.execute(myRunnable);
  18.         //抛出异常
  19.         pool.execute(myRunnable);
  20.     }
  21. }
  22. /**
  23. * 功能:用线程池实现Runnable对象
  24. */
  25. class myRunnable implements Runnable {
  26.     @Override
  27.     public void run() {
  28.         for (int i = 0; i < 5; i++) {
  29.             System.out.println(Thread.currentThread().getName() + "正在打印hello ==>" + i);
  30.         }
  31.         try {
  32.             System.out.println(Thread.currentThread().getName() + "开始睡眠");
  33.             Thread.sleep(1000000);
  34.         } catch (Exception e) {
  35.             e.printStackTrace();
  36.         }
  37.     }
  38. }
复制代码
线程池处理Callable任务的方法
  1. public class Communication {
  2.     public static void main(String[] args) throws ExecutionException, InterruptedException {
  3.         //线程池创建(不变)
  4.         ExecutorService pool = new ThreadPoolExecutor(3,5,2,
  5.                 TimeUnit.MINUTES, new ArrayBlockingQueue<>(5),new ThreadPoolExecutor.AbortPolicy());
  6.                 //调用线程池的submit方法处理myCallable对象,并用Future Task的父类Future继承
  7.         Future<String> f1 = pool.submit(new myCallable(100));
  8.         Future<String> f2 = pool.submit(new myCallable(200));
  9.         Future<String> f3 = pool.submit(new myCallable(300));
  10.         Future<String> f4 = pool.submit(new myCallable(400));
  11.         Future<String> f5 = pool.submit(new myCallable(500));
  12.                 //调用get方法返回内容
  13.         System.out.println(f1.get());
  14.         System.out.println(f2.get());
  15.         System.out.println(f3.get());
  16.         System.out.println(f4.get());
  17.         System.out.println(f5.get());
  18.     }
  19. }
  20. /**
  21. * 功能:用线程池实现Callable线程对象
  22. */
  23. class myCallable implements Callable<String> {
  24.     private int n;
  25.     public myCallable(int n) {
  26.         this.n = n;
  27.     }
  28.     @Override
  29.     public String call() throws Exception {
  30.         int sum = 0;
  31.         for (int i = 0; i < n; i++) {
  32.             sum += i;
  33.         }
  34.         return Thread.currentThread().getName() + "计算的1-" + n + "结果为" + sum;
  35.     }
  36. }
复制代码
方式二:使用Executors(线程池的工具类)调用方法返回不同线程池对象【非重点】

Executors工具类底层是ThreadPoolExecutor,但在大型并发系统环境使用Executors可能出现系统风险

  1.         ExecutorService pool = Executors.newFixedThreadPool(固定线程个数)
  2.     //底层调用ThreadPoolExecutor,仅有核心线程
复制代码
定时器

一种控制任务延时调用,或者周期调用的技术
实现方式::①Timer        ②ScheduledExecutorService定时器
Timer定时器
  1. Timer timer = new Timer();
  2. //schedule还有其他几种重载方式,见jdk
  3. timer.schedule(new TimerTask() {
  4.     @Override
  5.     public void run() {
  6.         //线程内容1
  7.     }
  8. },0,2000);
  9.    
  10. timer.schedule(new TimerTask() {
  11.     @Override
  12.     public void run() {
  13.         //线程内容2
  14.     }
  15. },0,2000);
复制代码
Timer定时器存在的问题
1、Timer定时器是单线程,处理多个任务顺序执行,存在延时问题
2、因为是单线程,若Timer线程死掉,会影响后续任务执行
ScheduledExecutorService定时器

ScheduledExecutorService内部是一个线程池,一个任务不会干扰其他任务
ScheduledExecutorService在日常开发中更加常用
  1. public static void main(String[] args) {
  2.         //
  3.     ScheduledExecutorService timer = new ScheduledThreadPoolExecutor(3);
  4.     //scheduleAtFixedRate表示以固定频率定时
  5.     timer.scheduleAtFixedRate(new Runnable() {
  6.         @Override
  7.         public void run() {
  8.             System.out.println("定时1" + new Date());
  9.         }
  10.     },0,2,TimeUnit.SECONDS);
  11.    
  12.     timer.scheduleAtFixedRate(new Runnable() {
  13.         @Override
  14.         public void run() {
  15.             System.out.println("定时2" + new Date());
  16.         }
  17.     },0,3,TimeUnit.SECONDS);
  18. }
复制代码
线程生命周期




免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

饭宝

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表