线程基础

  1. jps命令查看 pid

  2. 查看线程的堆栈: jstack pid

  3. 运行java监视和管理控制台: jconsole

  4. 并发编程的挑战

    1. 硬件资源: 带宽上传\下载速度、硬盘读写速度、cpu处理速度
    2. 软件资源: 数据库连接数、socket连接数、
  5. 进程与线程的区别

  6. 进程是系统进行分配和管理资源的基本单位

  7. 线程:进程的一个执行单元,是进程内调度的实例,是cpu调度和分派的基本单位,是比进程更小的独立运行的基本单位,线程也被称为轻量级进程,线程是程序执行的最小单位。

  8. 一个程序至少一个进程,一个进程至少一个线程。

  9. 进程有自己的独立地址空间,没启动一个进程,系统就会为他分配地址空间,建立数据表来维护代码段、堆栈段和数据段,这种操作非常昂贵。

  10. 线程共享进程中的数据,使用相同的地址空间,因此cpu切换一个线程的花费远比进程要小的多,同时创建一个线程的开销也比进程要小的多。

  11. 线程之间的通信更加方便,同一个进程下的线程共享全局变量、静态变量等数据,而进程之间的通信需要以通信的方式进行。

  12. 处理好同步与互斥是编写多线程程序的难点。

  13. 线程的状态及其相互转换

    • 初始new: 新创建了一个线程对象,但还没有调用start方法。
    • 运行Runnable:处于可运行状态的线程正在jvm中执行,但它可能正在等待来自操作系统的其他资源,如处理器。调用start后。
    • 阻塞Blocked: 线程阻塞于synchronized锁,等待获取synchronized锁的状态。
    • 等待(waiting): Object.wait(), join()。
    • LockSupport.park(): 进入该状态的线程需要等待其他线程作出一些特定操作(通知或中断)。
    • 超时等待(TIME_WAITING):Object.wait(long), Thread.join(), LockSupport.parkNanos(), LockSupport.parkUntil, 该状态不同于WAITING,它可以在指定时间内自行返回。
    • 终止(TERMINATE): 表示线程已经执行完毕。
  14. 创建一个线程, 方式一继承Thread并重写run方法

    public class MyThread extends Thread {
        @Override
        public void run() {
            System.out.println("name: "+Thread.currentThread().getName());
        }
        public static void main(String[] args) {
            MyThread thread = new MyThread();
            thread.setName("MyThread");
            thread.start();
        }
    }
    
  15. 创建一个线程, 方式二实现Runnable接口,并实现run方法

    public class MyRunnabe implements Runnable {
    
        @Override
        public void run() {
            System.out.println("name: "+Thread.currentThread().getName());
        }
    
        public static void main(String[] args) {
            Thread thread = new Thread(new MyRunnabe());
            thread.setName("MyRunnabe");
            thread.start();
        }
    
    }
    
  16. 实际开发中选第二种,

    1. 因为java只允许单继承,但可以实现多个接口;
    2. 增加程序的健壮性,代码可以共享,代码跟数据相对独立;
  17. start和run的区别

    • run只是方法的调用,程序依然在当前主线程

    • start开启一个新线程

  18. 匿名内部类的方式启动一个线程

    public class MyThread {
        public static void main(String[] args) {
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.println("name: "+Thread.currentThread().getName());
                }
            });
            thread.start();
        }
    }
    
  19. Lambda的方式启动一个线程

    public class Lambda {
        public static void main(String[] args) {
            new Thread(() -> {
                System.out.println("name: "+Thread.currentThread().getName());
            }).start();
        }
    }
    
  20. 使用线程池启动一个线程

    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    
    public class ThreadPool {
    
        public static void main(String[] args) {
            ExecutorService executorService = Executors.newSingleThreadExecutor();
            executorService.execute(() -> {
                System.out.println("name: "+Thread.currentThread().getName());
            });
        }
    }
    
  21. 线程的挂起:线程的挂去实质上就是使线程进入非可执行状态,在这个状态下CPU不会分给线程时间片,进入这个状态可以用来暂停一个线程的运行。在线程挂起后可以通过重新唤醒唤醒线程实质恢复运行。

  22. CPU分配的时间片很短,也很珍贵,挂起线程避免资源的浪费。

  23. 挂起线程的方式一(已废弃,不会释放所占有的资源,可能会引发死锁)

    thread.suspend();   //挂起一个线程,已废弃, 不会释放所占有的资源,可能会引发死锁
    thread.resume();    //唤醒一个线程,已废弃
    
  24. 线程的挂起和恢复

    public class SuspendDemo implements Runnable{
    
        public static void main(String[] args) throws Exception{
            Thread thread = new Thread(new SuspendDemo());
            thread.start();
            Thread.sleep(3000L);
            thread.resume();
        }
    
        @Override
        public void run() {
            System.out.println("开始name: "+Thread.currentThread().getName());
            Thread.currentThread().suspend();
            System.out.println("结束name: "+Thread.currentThread().getName());
        }
    }
    
  25. 挂起可能会导致死锁

    /**
     * 挂起会导致死锁
     */
    public class DeadDemo implements Runnable{
    
        private static Object obj = new Object();
    
        public static void main(String[] args) throws Exception{
            Thread thread = new Thread(new DeadDemo(), "对比线程");
            thread.start();
            Thread.sleep(1000L);
            thread.resume();
    
            Thread dead = new Thread(new DeadDemo(), "死锁线程");
            dead.start();
            //Thread.sleep(3000L);
            dead.resume();
        }
    
        @Override
        public void run() {
            //持有资源
            synchronized (obj) {
                System.out.println(Thread.currentThread().getName() +"持有资源");
                Thread.currentThread().suspend();
            }
            System.out.println(Thread.currentThread().getName() +"释放了资源");
        }
    }
    
  26. 挂起线程的方式二

    wait();       //暂停执行,放弃已经获得的锁,进入等待状态,可以使用
    notify();     //可以使用
    notifyAll();  //唤醒所有的线程
    
  27. wait挂起线程

    public class WaitDemo implements Runnable {
    
        private static Object waitObj = new Object();
    
        public static void main(String[] args) throws Exception{
            Thread thread = new Thread(new WaitDemo(), "对比线程");
            thread.start();
    
            Thread thread2 = new Thread(new WaitDemo(), "对比线程2");
            thread2.start();
            thread2.sleep(3000L);
    
            synchronized (waitObj) {
                waitObj.notify();
            }
        }
    
        @Override
        public void run() {
            //持有资源
            synchronized (waitObj) {
                System.out.println(Thread.currentThread().getName() +"持有资源");
                try {
                    waitObj.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(Thread.currentThread().getName() +"释放了资源");
        }
    }
    
  28. 什么时候使用线程:等待某些未就绪的资源,知道notify方法被调用。

  29. 线程的终端:

  30. stop(被废弃,开发中不要使用,已调用线程立刻停止,有可能会导致响应的线程安全性问题)

    public class UnsafeWithStop extends  Thread{
    
        private int i = 0;
        private int j = 0;
    
        @Override
        public void run() {
            i++;
            try {
                sleep(2000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            j++;
        }
    
        public void print(){
            System.out.println("i: "+i);
            System.out.println("j: "+j);
        }
    
        public static void main(String[] args) throws InterruptedException {
            UnsafeWithStop unsafeWithStop = new UnsafeWithStop();
            unsafeWithStop.start();
            Thread.sleep(1000L);
            unsafeWithStop.stop();
            unsafeWithStop.print();
        }
    }
    
  31. interrupt

    /**
     * interrupt中断线程,打一个标志位,等待当前线程执行结束,不会立即终止
     */
    public class InterruptDemo implements Runnable {
        @Override
        public void run() {
            while (!Thread.currentThread().isInterrupted()) {
                System.out.println("name: "+Thread.currentThread().getName());
            }
        }
    
        public static void main(String[] args) throws InterruptedException {
            Thread thread = new Thread(new InterruptDemo());
            thread.start();
            Thread.sleep(1000);
            thread.interrupt();
        }
    }
    
  32. 中断线程的第三种方式

    /**
     * 设置标志位中断线程
     */
    public class MyInterruptDemo implements Runnable {
    
        private static volatile boolean FLAG = true;
    
        @Override
        public void run() {
            while (FLAG){
                System.out.println("name: "+Thread.currentThread().getName());
            }
        }
    
        public static void main(String[] args) throws InterruptedException {
            Thread thread = new Thread(new MyInterruptDemo());
            thread.start();
            Thread.sleep(1000L);
            FLAG = false;
        }
    }
    
  33. 线程的优先级:线程的优先级告诉程序该线程的重要性,如果有大量的线程被阻塞,在等待运行,程序会尽可能先的执行优先级高的线程。

  34. 线程的优先级的值: 1到10,默认为5

    public class PriorityDemo  {
    
        public static void main(String[] args) {
            Thread thread = new Thread(() -> {
                while (true){
                    System.out.println("name: "+Thread.currentThread().getName());
                    /*try {
                        Thread.sleep(30L);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }*/
                }
            }, "线程1");
    
            Thread thread2 = new Thread(() -> {
                while (true){
                    System.out.println("name: "+Thread.currentThread().getName());
                    /*try {
                        Thread.sleep(30L);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }*/
                }
            }, "线程2");
    
            thread.setPriority(Thread.MIN_PRIORITY);
            thread2.setPriority(Thread.MAX_PRIORITY);
    
            thread.start();
            thread2.start();
        }
    }
    
  35. 不同的平台对线程的优先级的支持不同,在编程的时候不要过度依赖线程优先级,如果程序运行正确取决于设置的优先级,那这样的程序是不正确的。

  36. 需要快速处理的,可以设置高的优先级,需要慢慢处理的,可以设置低的优先级。

  37. 线程分为用户线程和守护线程

    • 用户线程: 线程为执行完成之前,程序不会退出。
    • 守护线程: 尽量减少使用守护线程,因其不可控,不要在守护线程里进行读写操作,执行计算逻辑,
  38. 开启守护线程的方式

    thread.setDaemon(true);  //在调用start之前
    thread.start();
    
  39. 线程安全: 当多个线程访问某个对象,不管运行时环境采用何种调度方式或者这些线程如何交替执行,并且在主调代码中不需要任何额外的同步或协同,这个类都能表现出正确的行为,那么这个类就成为线程安全的。

  40. 线程不安全: 多个线程并发访问时,得不到正确的结果。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值