Java 线程

线程

创建线程的方式

  1. 继承Thread,并实现run方法;new一个对象,调用start()方法,开启一个线程

  2. 实现Runnable接口,并实现run 方法,new Thread对象,把Runnable的实现类放到里面,然后调用Thread的start方法。

public class useThread {
​
    public static void main(String[] args) {
​
//        extendThread extendThread = new extendThread();
//        extendThread extendThread1 = new extendThread();
//        extendThread.setName("thread 1");
//        extendThread1.setName("thread 2");
//
//        // 调用 run方法,只是普通的调用方法,调用start才是启动一个新的线程。
//        extendThread.start();
//        extendThread1.start();
​
        importThread importThread = new importThread();
        importThread importThread1 = new importThread();
​
        Thread t1 = new Thread(importThread);
        Thread t2 = new Thread(importThread1);
​
        t1.setName("thead 1");
        t2.setName("thread 2");
​
        t1.start();
        t2.start();
​
    }
​
}
​
​
//继承
class extendThread extends Thread{
​
    //从写run
    @Override
    public void run() {
        for(int i = 0 ;i < 100 ;i ++ )
            System.out.println( getName() +"继承Thread类");
    }
}
​
//实现
class importThread implements Runnable{
​
    @Override
    public void run() {
        for (int i = 0; i < 100; i++){
            //获得当前线程
            Thread thread = Thread.currentThread();
            System.out.println(thread.getName() + "Hello,world!");
        }
    }
}
  1. 使用Callable 和 Future;这种方式可以获得多线程运行的结果;创建一个类实现Callable<ReturnValue> ,泛型是多线程要返回的结果;创建一个类,实现Callable接口,重写call方法,创建一个实现类的对象(表示要执行的对象),创建FutureTask对象(管理多线程运行的结果),创建Thread类对象,启动;通过FutureTask对象可以获得线程执行的结果。

public class useThread {
​
    public static void main(String[] args) {
​
        myCallable myCallable = new myCallable();
​
        FutureTask<Integer> ft = new FutureTask<>(myCallable);
​
        Thread thread = new Thread(ft);
​
        thread.start();
​
        //获取线程调用结果
        try {
            System.out.println("多线程调用的结果:" + ft.get());
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
​
    }
​
}
​
class myCallable implements Callable<Integer> {
    /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * @return computed result
     * @throws Exception if unable to compute a result
     */
    @Override
    public Integer call() throws Exception {
        int sum = 0;
        for(int i = 1;i <= 100 ;i +=1 ) sum += i;
        return sum;
    }
}

选择:

简单就选继承Thread,需要扩展用Runable接口;需要结果就Callable。

常用的成员方法

  1. getName() ,可以使用t.setName('')设置线程名字,默认是Thread-0。

  2. setName()或者创建对象的使用可以使用 Thread(String name) 这个构造器。

    1. 构造方法是不能继承的,如果子类想要使用父类的构造方法,可以自己写一个构造方法,然后去调用父类的构造方法。

  3. currentThread() -- static获得当前运行的线程,可以获得线程信息。

    1. 当JVM启动后,会自动调用多条线程,其中一条线程就是main线程,它的作用就是执行main方法,并执行里面的内容。

  4. sleep() -- static让线程休眠

    1. 那条线程执行这个方法,就停留多少时间,单位是毫秒。

    2. 当时间到了之后,会继续执行下面的代码。

    3. 父类中的方法没有抛出异常,继承后的子类方法,也就不能抛出异常,必须使用try-catch

  5. setPriority(int newPriority) 设置线程的优先级。

    1. 默认是5,最大是10,最小是1。

    2. priority越大,被执行的概率越高,但并不是按照比例去执行。

  6. setDaemon(boolean on) 设置为守护线程。

    1. 当其他的非守护线程执行完毕之后,守护线程会陆续结束。

    2. 应用场景:聊天和文件的上传,当聊天关闭的时候,文件也没有上传的必要了,所以:在这里文件上传就是守护线程。

  7. yield() -- static 出让线程

    1. 只是出让,但是不一定也会让别人抢到线程。

  8. join() 插入线程

    1. 插入线程到当前线程之前,只有等到插入的线程执行完之后,才会执行当前线程。

线程的生命周期

不安全的问题

public class part1 {
    public static void main(String[] args) throws InterruptedException {
        myThread t1 = new myThread("window1");
        myThread t2 = new myThread("window2");
        myThread t3 = new myThread("window3");
        t2.start();
        t1.start();
        t3.start();
    }
}
class myThread extends Thread{
​
    public myThread(String name){
        super(name);
    }
​
    public myThread(){
        super();
    }
​
    static int ticket = 0;
​
    @Override
    public void run() {
        while(true){
            if(ticket < 100){
                try {
                    Thread.sleep(100);
                }catch (InterruptedException e){
                    System.err.println("kkkkk");
                }
                ticket ++;
                System.out.println( getName() +  "已经买到了 ===> " + ticket);
            }else{
                break;
            }
        }
    }
}

出现重复售票

  • cpu的执行权,随时可能被其他线程抢占。

票多买

  • 在99的时候,通过有多个线程进入while循环。

解决方案:---- 加锁

同步代码块

synchronized(里的锁对象一定要是唯一的)

public class part1 {
    public static void main(String[] args) throws InterruptedException {
        myThread t1 = new myThread("window1");
        myThread t2 = new myThread("window2");
        myThread t3 = new myThread("window3");
        t2.start();
        t1.start();
        t3.start();
    }
}
class myThread extends Thread{
​
    public myThread(String name){
        super(name);
    }
​
    public myThread(){
        super();
    }
​
    static int ticket = 0;
​
    //锁对象一定是唯一的。
    static Object obj = new Object();
​
    @Override
    public void run() {
        while(true){
            synchronized (obj){
                if(ticket < 100){
                    //锁住操作票的代码
                    try {
                        Thread.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "窗口出售第" + ++ticket + "票");
                }else{
                    break;
                }
            }
        }
    }
}

同步方法

修饰符 synchronized 返回值类型 方法名() {....}

特点

  1. 同步方法锁住的是方法里的全部代码

  2. 锁对象不能指定:

    1. 非静态: this

    2. 静态: class

锁对象是:this,也能保持线程同步,因为这里始终都是一个对象。

public class part1 {
    public static void main(String[] args) throws InterruptedException {
        myThread1 myThread1 = new myThread1();
​
​
        new Thread(myThread1,"窗口2").start();
        new Thread(myThread1,"窗口1").start();
​
​
    }
}
​
​
class myThread1 implements Runnable{
​
    int ticket = 0 ;   //注意这里的ticket并不用一定是静态的,因为这个对象创建后,是作为参数在Thread执行的,只有一份
​
    @Override
    public void run() {
        while(true){
            if (extracted()) break;
        }
    }
​
    private synchronized boolean extracted() {
        if(ticket < 100){
            //锁住操作票的代码
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "窗口出售第" + ++ticket + "票");
        }else{
            return true;
        }
        return false;
    }
}

Lock

public class part1 {
    public static void main(String[] args) throws InterruptedException {
        new myThread("窗口1").start();
        new myThread("窗口2").start();
    }
}
​
class myThread extends Thread{
​
    public myThread(String name){
        super(name);
    }
​
    public myThread(){
        super();
    }
​
    static int ticket = 0;
​
    //需要共享同一把锁
    static Lock lock = new ReentrantLock();
​
​
    @Override
    public void run() {
        while(true){
​
            //锁住操作票的代码
            lock.lock();
            if(ticket < 100){
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "窗口出售第" + ++ticket + "票");
​
​
            }else{
                break;
            }
            lock.unlock();
        }
    }
}

上面这段代码有点问题,如果通过if break了,跳出循环后,就会导致锁没有释放,然后就会导致程序堵塞,稳妥的写法是把释放锁的操作放的finally中进行,因为无论如何finally中的代码肯定是要执行的。

@Override
public void run() {
    while(true){
        //锁住操作票的代码
        lock.lock();
        try {
            if(ticket < 100){
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "窗口出售第" + ++ticket + "票");
            }else{
                break;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }
}

死锁

死锁是一个常见的错误。

public class part1 {
    public static void main(String[] args) throws InterruptedException {
        new myThread("a").start();
        new myThread("b").start();
    }
}
class myThread extends Thread{
​
    public myThread(String name){
        super(name);
    }
​
    static Object objA = new Object();
    static Object objB = new Object();
​
    @Override
    public void run() {
        while(true){
            if("a".equals(this.getName())){
                synchronized (objA){
                    System.out.println("线程A拿到A锁,准备拿B锁");
                    synchronized (objB){
                        System.out.println("线程A拿到B锁,执行完成!");
                    }
                }
            }else if("b".equals(this.getName())){
                synchronized (objB){
                    System.out.println("线程B拿到B锁,准备拿A锁");
                    synchronized (objA){
                        System.out.println("线程B拿到A锁,执行完成!");
                    }
                }
            }
        }
    }
}

生产者和消费者

生产者消费者模式是一个十分经典的多线程协作的模式。

生产者

//生产者线程
public class Cook extends Thread{
​
    @Override
    public void run() {
        while(true){
            synchronized (dest.lock){
                if(dest.count == 0){
                    break;
                }else{
                    //判断桌子上是否有食物
                    if(dest.status == 1){
                        try {
                            dest.lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }else{
                        //没有食物
                        System.out.println("做了一碗");
                        //修改桌子上食物的状态
                        dest.status = 1;
                        //叫醒消费者
                        dest.lock.notifyAll();
                    }
                }
            }
        }
    }
}

消费者

public class Foodie extends Thread{
​
    public void run() {
        /*
            1.循环生产
            2.同步代码
            3.判断共享数据
         */
​
        while(true){
            synchronized (dest.lock){
                if(dest.count == 0)
                    break;
                else{
                    //判断桌子上是否有面条
                    if(dest.status == 0){
                        // 没有就等待,唤醒厨师
                        System.out.println("厨师生产面条");
                        try {
                            dest.lock.wait();  //让当前线程根锁进行绑定
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }else{
                        //把吃的总数--
                        dest.count -- ;
                        // 有就开吃
                        System.out.println("开吃,开吃,还剩下 " + dest.count+ " 碗");
                        // 吃完之后,厨师继续做饭
                        dest.lock.notifyAll();  //唤醒所有的线程
                        //修改桌子的状态
                        dest.status = 0;
                    }
                }
            }
        }
    }
}
//控制生产者和消费者的执行
public class dest {
    
    public static int status = 0;
    public static int count = 10 ;
    //锁对象
    public static final Object lock = new Object();
}

等待唤醒机制(阻塞队列)

生产者

public class Cook extends Thread{
​
    ArrayBlockingQueue<String> queue;
​
    public Cook(ArrayBlockingQueue<String> queue) {
        this.queue = queue;
    }
​
    @Override
    public void run() {
        while(true){
            //不断地把面条放到阻塞队列中去
            try{
​
                queue.put("面条");
                System.out.println("厨师放了一碗面条");
            } catch(Exception e){
                e.printStackTrace();
            }
        }
    }
}

消费者

public class Foodie extends Thread{
​
    ArrayBlockingQueue<String> queue;
​
    public Foodie(ArrayBlockingQueue<String> queue)
    {
        this.queue = queue;
    }
​
    @Override
    public void run() {
        while(true){
            try {
                String peek = queue.take();
                System.out.println(peek);
            }catch (Exception  e){
                e.printStackTrace();
            }
        }
    }
}

Test

public class Test {
    public static void main(String[] args) {
​
        ArrayBlockingQueue<String> strings = new ArrayBlockingQueue<String>(3);
​
        Cook cook = new Cook(strings);
        Foodie foodie = new Foodie(strings);
​
        cook.start();
        foodie.start();
​
    }
}

ArrayBlockingQueueLinkedBlockingQueue实现的接口有Queue,Collection,BlockingQueue和Iterator等接口。

ArrayBlockingQueue 底层是数组,需要指定队列大小。

put放入一个元素。

public void put(E e) throws InterruptedException {
    checkNotNull(e);
    final ReentrantLock lock = this.lock;
    lock.lockInterruptibly();
    try {
        //如果当前队列是满的,就等待。
        while (count == items.length)
            notFull.await();
        //否则就入队。
        enqueue(e);
    } finally {
        //最后释放锁。
        lock.unlock();
    }
}

take往队列拿出一个元素。

public E take() throws InterruptedException {
    final ReentrantLock lock = this.lock;
    lock.lockInterruptibly();
    try {
        //如果队列长度是0,就等待。
        while (count == 0)
            notEmpty.await();
        //否则就拿出一个元素。
        return dequeue();
    } finally {
        //最后释放锁
        lock.unlock();
    }
}

线程的状态

  1. new -- 新建 -- 创建线程对象

  2. Runable -- 可执行状态 -- start方法

  3. Blocked -- 阻塞状态 -- 无法获得锁对象

  4. Waiting -- 等待状态 -- wait方法

  5. Timed_Waitting -- 计时等待状态 -- sleep方法

  6. Terminated -- 结束状态 -- 全部代码执行完毕

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值