阿里面试官:你连个java多线程都说不清楚,我招你进来干什么
阅读原文时间:2023年07月09日阅读:2
  • 继承Thread类

  • 继承Thread类,重写run方法,通过线程类实例.start()方法开启线程。

    public class TestThread1 extends Thread{
    @override
    public void run(){
    System.out.println("线程run方法!");
    }

    public static void main(String){
        new TestThread1().start();
    }

    }

  • 实现Runnable接口

  • 实现Runnable接口,重写run方法,通过new Thread(线程类实例).start()开启线程

  • 推荐使用该方式,避免java的单继承局限性

    public class TestThread2 implements Runnable{
    @Override
    public void run() {
    System.out.println("线程run方法!");
    }

    public static void main(String[] args) {
        new Thread(new TestThread2()).start();
    }

    }

  • 实现Callable接口

  • 实现Callable接口,重写call方法,call方法有返回值

  • 启动方式:

    • 创建执行服务

    • 提交执行

    • 获取结果

    • 关闭服务

    public class TestThread2 implements Callable{
    @Override
    public Boolean call() {
    System.out.println("线程call方法!");
    return true;
    }

    public static void main(String[] args) throws InterruptedException, ExecutionException {
    TestThread2 t1 = new TestThread2();
    TestThread2 t2 = new TestThread2();
    TestThread2 t3 = new TestThread2();
    //创建执行服务
    ExecutorService ser = Executors.newFixedThreadPool(3);
    //提交执行
    Future<Boolean> r1 = ser.submit(t1);
    Future<Boolean> r2 = ser.submit(t2);
    Future<Boolean> r3 = ser.submit(t3);
    //获取结果
    boolean rs1 = r1.get();
    boolean rs2 = r2.get();
    boolean rs3 = r3.get();
    //关闭服务
    ser.shutdownNow();
    }
  • 多个线程同时操作同一资源,线程不安全,变量值紊乱

  • 加锁

  • 队列+锁(synchronized)

  • synchronized默认锁this,可以显示指定锁的对象来修改

1. synchronized修饰方法,线程安全方法

public class TestThreadSafe {

    public static void main(String[] args) {
        BuyTicket bt1 = new BuyTicket();

        Thread thread1 = new Thread(bt1,"张三");
        Thread thread2 = new Thread(bt1,"李四");
        Thread thread3 = new Thread(bt1,"黄牛");

        thread1.start();
        thread2.start();
        thread3.start();
    }

}

class BuyTicket implements Runnable{

    private int ticketNumber = 10;

    private boolean flag = true;

    @Override
    public void run() {
        while(flag) {
            try {
                buy();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public synchronized void buy() throws InterruptedException {
        //买票
        if(ticketNumber <= 0){
            System.out.println("票卖完了!");
            flag = false;
            return;
        }
        Thread.sleep(100);
        //Thread.yield();
        System.out.println(Thread.currentThread().getName() + "买到了一张票,还剩下"+(--ticketNumber) + "张票!");
    }
}

2. synchronized修饰代码块,线程安全代码块

public class TestThreadSafe {

    public static void main(String[] args) {
        BuyTicket bt1 = new BuyTicket();

        Thread thread1 = new Thread(bt1,"张三");
        Thread thread2 = new Thread(bt1,"李四");
        Thread thread3 = new Thread(bt1,"黄牛");

        thread1.start();
        thread2.start();
        thread3.start();
    }

}

class BuyTicket implements Runnable{

    private int ticketNumber = 10;

    private boolean flag = true;

    @Override
    public void run() {
        while(flag) {
            System.out.println(Thread.currentThread().getName() + "准备买票" + flag);
            try {
                buy();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void buy() throws InterruptedException {
        synchronized(this){
            //买票
            if(ticketNumber <= 0){
                flag = false;
                System.out.println("票卖完了!");
                return;
            }
            Thread.sleep(100);
            //Thread.yield();
            System.out.println(Thread.currentThread().getName() + "买到了一张票,还剩下"+(--ticketNumber) + "张票!");
        }
    }
}

3. 使用可重复锁ReentrantLock

import java.util.concurrent.locks.ReentrantLock;

public class TestLock {

    public static void main(String[] args) {
        BuyTicket bt1 = new BuyTicket();

        Thread thread1 = new Thread(bt1,"张三");
        Thread thread2 = new Thread(bt1,"李四");
        Thread thread3 = new Thread(bt1,"黄牛");

        thread1.start();
        thread2.start();
        thread3.start();
    }

}

class BuyTicket implements Runnable{

    private int ticketNumber = 1000;

    private boolean flag = true;

  //定义可重复锁
    private    final ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        while(flag) {
            try {
                buy();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void buy() throws InterruptedException {
            lock.lock();
            //买票
            if(ticketNumber <= 0){
                System.out.println("票卖完了!");
                flag = false;
            }else {
                Thread.sleep(100);
                //Thread.yield();
                System.out.println(Thread.currentThread().getName() + "买到了一张票,还剩下"+(--ticketNumber) + "张票!");
            }
            lock.unlock();
    }
}
  • 死锁

  • 两个以上的对象锁,每个线程互相占有对方需要的资源。形成死锁。

  • 新生状态(new)

  • 就绪状态(start)

  • 阻塞状态(sleep、wait、同步锁定)

  • 运行状态

  • 死亡状态 线程对象进入死亡状态后,将不能再次调用start()方法再次启动

  • setPriority(int newPriority) 更改线程优先级 newPriority从1到10

  • static void sleep(long millis) 使当前正在执行的线程休眠指定毫秒,不会释放线程锁对象

  • void join() 线程合并,等待该线程终止

  • static void yield() 暂停当前正在执行的线程,执行其它线程

  • void interrupt() 中断线程

  • boolean isAlive() 该线程是否活跃

  • setDaemon(true) : 设置为守护线程

  • 线程分为用户线程和守护线程

  • JVM虚拟机确保用户线程执行完毕

  • JVM虚拟机不用等待守护线程执行完毕

         eg:后台记录操作日志,监控内存,垃圾回收等待

感谢你看到这里,看完有什么的不懂的可以在评论区问我,觉得文章对你有帮助的话记得给我点个赞,每天都会分享java相关技术文章或行业资讯,欢迎大家关注和转发文章!