《Java并发编程的艺术》并发编程的基础(四)

川长思鸟来 2021-12-03 07:19 465阅读 0赞

一、线程简介

1.线程的概念

系统运行的最小单元

2.为何使用多线程

更好地利用系统资源(处理器多核心),提高响应速度。

3.线程的状态

  1. NEW(创建状态)
  2. RUNABLE(运行状态,系统调度,争抢时间片)
  3. BLOCKED(阻塞状态,加了锁,其它线程获得到了锁)
  4. WATING(等待状态,wait()方法时,使用notify()唤醒)
  5. TIMED_WAITING(超时等待状态,线程sleep()时,)
  6. TERMINAL(线程终止)

关于wait和notify:

  1. public class ThreadTest {
  2. public static void main(String[] args) throws InterruptedException {
  3. Thread thread = new Thread(new Waiting(), "WaitingThread");
  4. Thread thread2 = new Thread(new NotifyWaiting(), "NotifyWaitingThread");
  5. thread.start();
  6. TimeUnit.SECONDS.sleep(2);
  7. thread2.start();
  8. }
  9. }
  10. class Waiting implements Runnable {
  11. @Override
  12. public void run() {
  13. synchronized (Waiting.class) {
  14. try {
  15. System.out.println("Current thread: " + Thread.currentThread().getName() + ",Waiting is waiting!");
  16. Waiting.class.wait();
  17. System.out.println("Current thread: " + Thread.currentThread().getName() + ",Waiting is notified!");
  18. } catch (InterruptedException e) {
  19. e.printStackTrace();
  20. }
  21. }
  22. }
  23. }
  24. class NotifyWaiting implements Runnable {
  25. @Override
  26. public void run() {
  27. synchronized (Waiting.class) {
  28. Waiting.class.notify();
  29. System.out.println("Current thread: " + Thread.currentThread().getName() + ",Waiting is notified!");
  30. }
  31. }
  32. }

结果:

  1. Current thread: WaitingThread,Waiting is waiting!
  2. Current thread: NotifyWaitingThread,Waiting is notified!
  3. Current thread: WaitingThread,Waiting is notified!

wait方法会释放锁,sleep则不会

二、启动和终止线程

1.启动线程

1.构建线程

  1. new Thread();
  2. new Runable();
  3. new Callable(); //Callable可以返回Future携带返回值

注意:最好给线程初始化名称,方便JVM分析。

2.启动线程

  1. thread.start();

或者Excutors.new线程池,然后ExecutorService.submit或者excute

2.终止线程

终止线程最好使用一个volatile修饰的boolean开关去进行控制

转载于:https://www.cnblogs.com/lcmlyj/p/11008311.html

发表评论

表情:
评论列表 (有 0 条评论,465人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Java并发编程艺术

         什么是上下文切换: 上下文切换 即使是单核处理器也支持多线程执行代码,CPU通过给每个线程分配CPU时间片来实现 这个机制。时间片是CPU分配给各个线程的时间