关于java:阿里面试官你连个java多线程都说不清楚我招你进来干什么

6次阅读

共计 3944 个字符,预计需要花费 10 分钟才能阅读完成。

创立线程的办法

  • 继承 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()办法再次启动

线程(Thread 类)办法

  • 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 相干技术文章或行业资讯,欢送大家关注和转发文章!

正文完
 0