JavaEE多线程

 继承 Thread, 重写 run

以下代码中,两个线程的代码在并发执行。无规律的交叉打印hello thread和hello main,此时称为并行和并发执行,因为在写程序的时候,感知不到它是在两个核上同时执行,还是在一个核上先后执行。此时统称为并发执行,此时可以充分使用多核CPU资源

//创建一个类,继承java自带的Thread,此处不用import也可以使用,因为Thread是在java.lang包下,这个包下是不用import的
class MyThread extends Thread{
    //继承以后,要将父类中的方法重写
    @Override
    public void run() {
        //线程的入口方法
        while (true){
        System.out.println("hello thread");
        }
    }
}
public class demo1 {
    public static void main(String[] args) {
        Thread t = new MyThread();
        //start和run都是thread的成员。
        //run只是描述了线程的入口(线程要做什么任务)
        //start则是真正调用了系统API,在系统中创建出线程,让线程再调用run
        t.start();
        while (true){
            System.out.println("hello main");
        }
    }
}

如果把t.start()换成t.run(),此时则不会产生新的线程,只会有一个主线程。这个主线程里面只能从上往下依次执行,因此只会打印hello thread,死循环。

其实此时这种情况,就相当于调用另一个类中的方法。

public class demo1 {
    public static void main(String[] args) {
        Thread t = new MyThread();
        //start和run都是thread的成员。
        //run只是描述了线程的入口(线程要做什么任务)
        //start则是真正调用了系统API,在系统中创建出线程,让线程再调用run
        //t.start();
        t.run();
        while (true){
            System.out.println("hello main");
        }

    }
}

使用jconsole查看正在运行的进程。

在jconsole,可以看到一个最简单的java进程,里面也有很多线程,jvm自己创建的。Thread-0是自我创建的。         

未来写多线程程序的时候,就可以借助这个功能,来看到线程实时的运行情况。

实现Runnable,重写run

class MyRunnable implements Runnable{

    @Override
    public void run() {
        System.out.println("Hello MyRunnable");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

    }
}


public class demo2 {
    public static void main(String[] args) throws InterruptedException {
        //Runnable表示一个可以运行的任务,这个任务是交给线程负责执行,还是交给其他实体来执行
        //Runnable本身并不关心
        //终究还是通过t.start来调用系统api来完成创建线程的工作
        Runnable runnable = new MyRunnable();
        Thread t = new Thread(runnable);
        t.start();
        while (true){
            System.out.println("hello main");
            Thread.sleep(1000);
        }

    }
}

使用Runnable的写法,和直接继承Thread之间的区别,主要就是为了解耦合

创建一个线程,需要进行两个关键操作:

1.明确线程要执行的任务

2.调用系统api创建出线程

任务本身,不一定和线程概念强相关的,这个任务只是单纯的执行一段代码,这个任务是使用单个线程执行,还是多个线程执行,还是通过其他方法(信号处理函数,协程数,线程池......)都没什么区别~

可以把任务本身提取出来,此时就可以随时把代码改成其他方式来执行这个任务。

其实就相当于把 sout("hello myrunnable")这个要实现的内容,单独存放到一个myrunnable线程中。只是在main主线程中去调用这个线程中的方法。

继承Thread,重写run,但是使用匿名内部类

public class demo3 {
    public static void main(String[] args) throws InterruptedException {

        Thread t =new Thread(){
            @Override
            public void run() {
                while (true){
                    System.out.println("hello thread");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        };
        
        t.start();
        while (true){
            System.out.println("hello main");
            Thread.sleep(1000);
        }

    }
}

实现Runnable,重写run,但是使用匿名内部类

public class demo4 {
    public static void main(String[] args) throws InterruptedException {
//        Runnable runnable = new Runnable() {
//            @Override
//            public void run() {
//                while (true) {
//                    System.out.println("hello");
//                    try {
//                        Thread.sleep(1000);
//                    } catch (InterruptedException e) {
//                        throw new RuntimeException(e);
//                    }
//                }
//            }
//        };

        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    System.out.println("hello");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        });
        t.start();

        while (true){
            System.out.println("hello main");
            Thread.sleep(1000);
        }
    }
}

基于lambda表达式(最推荐写法)

lambda本质上是函数式接口(本质上还是没有脱离类)

public class demo5 {
    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread(() -> {
            while (true) {
                System.out.println("hello lambda");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        
        t.start();
        while (true){
            System.out.println("hello main");
            Thread.sleep(1000);
        }

    }
}

除了以上方法,还有其他方法,如线程池等。

关于Thread类的其他使用方式

创建线程的时候,可以指定name,name不影响线程的执行,只是给线程一个名字,目的是在后续调试的时候,比较方便区分。 

id就是身份证,表示进程中唯一的一个线程,是java分配的,不是系统api提供的线程id,更不是PCB中的id。

isDaemon又称守护线程(后台线程)。

前台线程:一个java进程中,如果前台线程没有执行结束,那么整个java进程一定不会结束的。相比之下,后台线程不结束,不会影响整个进程的结束。

public class demo6 {
    public static void main(String[] args) {
        Thread t = new Thread(() -> {
            while (true) {
                System.out.println("hello thread");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "线程名字");
        t.setDaemon(true);
        
        t.start();
    }
}

用 t.setDaemon(true) 改为后台线程以后,主线程飞快结束了,此时没有其他前台线程了,于是进程结束t线程来不及执行,进程就完了。

Thread对象的生命周期,要比系统内核中的线程更长一些。可能存在Thread对象还在,而内核中线程已经销毁了这样的情况。(并非同年同月同日死)

isAlive()判定内核线程是不是已经没了(回调方法执行完毕,线程才真的没了)。

public class demo7 {
    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread(
                ()->{
                    System.out.println("线程开始");
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    System.out.println("线程结束");
                }
        );

        t.start();
        System.out.println(t.isAlive());
        Thread.sleep(3000);
        System.out.println(t.isAlive());
    }
}

start和run的区别

start方法内部,会调用到系统api,在系统内核会创建出线程。

run方法,仅仅就是描述了该线程要执行的内容(会在start创建好线程之后,自动被调用)

终止一个线程interrupt

让一个线程停止运行(销毁)

在java中,想销毁/终止一个线程,做法比较唯一,就是想办法让run尽快执行结束。

1、可以在代码中手动创建出标志位,来作为run的执行结束的条件。

许多程序执行时间久,就是因为在这其中循环要执行很长时间。要想让run执行结束,就让循环快速结束。

此处isQuit是成员变量,如果把他改成main方法中的局部变量可以吗?

不可以,lambda表达式存在变量捕获,可以让lambda表达式把当前作用域中的变量复制了一份。根本原因在于不能修改。在java中,变量捕获语法还有一个前提限制,就是必须只能捕获一个final或者实际上是final的变量。变量虽然没有使用final修饰,但是却没有修改内容,此时也认为他是final。如果把isQuit改为成员变量时,此时lambda访问这个成员,就不再是变量捕获的语法了,而是“内部类访问外部类属性了”,这是两种不同的访问方式,此时就没有final之类的限制了。

public class demo8 {
    private static boolean isQuit = false;

    public static void main(String[] args) throws InterruptedException {

        Thread t = new Thread(()->{
            while (!isQuit){
                //此处打印可以替换成任意其他逻辑
                System.out.println("线程工作中");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            System.out.println("线程工作完毕");
        });
        t.start();
        Thread.sleep(5000);
        isQuit = true;
        System.out.println("设置isQuit为true");
    }
}

上述方案不够优雅:1.要手动创建变量。2.当线程内部在sleep的时候,主线程修改变量,新线程内部不能及时响应。因此就需要使用另外的方式来完成上述线程中断的操作。

//线程终止
public class demo9 {
    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread(() -> {
            //thread类内部,就有一个现成的标志位,可以用来判定当前循环是否结束
            while (!Thread.currentThread().isInterrupted()){
                System.out.println("线程工作中");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    //1.假装没听见,循环正常执行
                    e.printStackTrace();
                    //2.加上一个break,表示让线程立刻结束
                    break;
                    //3.做一些其他工作,完成之后再结束,在break前面加一点其他工作
                }
            }
        });
        t.start();
        Thread.sleep(5000);
        System.out.println("线程终止");
        t.interrupt();
    }
}

使用Thread自带的方法,Thread.currentThread().isInterrupted()

Thread.currentThread()是指获取当前线程的实例化对象,也就是Thread t。

Thread内部有一个标志位,这个标志位就可以用来判定线程是否结束。 

正常来说,sleep会休眠到时间到,才能唤醒,此处给出的interrupt就可以使sleep内部触发一个异常,从而提前被唤醒。这是自己手动设置无法做到的。

interrupt唤醒线程后,此时sleep方法抛出异常,同时它也会清除刚才的标志位。这就使得设置标志位的工作好像没实现一样(其实生效了)。

为什么要这样设定呢?是因为java是期望当线程收到要中断这样的信号时,他能够自由决定接下来如何处理。线程有3中操作

线程等待

让一个线程等待另一个线程执行结束再执行,本质上是让控制线程的结束顺序。

join实现线程等待的效果。

主线程中,调用t.join(),此时就是主线程等待t线程先结束。实际开发中不建议死等,会设置一个时间,超时就还是往下执行。

public class demo10 {
    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                System.out.println("t线程工作中");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t.start();
        //让主线程等待t线程执行结束
        //一旦调用join,主线程就会触发阻塞,此时t线程就可以乘机完成后续工作
        //一直阻塞到t执行完毕,join才会接触阻塞,继续执行
        System.out.println("join 等待开始");
        t.join();
        System.out.println("join 等待结束");
    }
}

线程状态

最核心的状态就是就绪状态和阻塞状态

在java中又给线程赋予了一些其他的状态

NEW:当前Thread对象已经有了,start方法还没调用

TERMINATED:Thread对象还在,内核中的线程已经没了

RUNNABLE:就绪状态(线程已经在cpu上执行了 / 线程正在排队等待上cpu执行)

TIME_WAITING:阻塞状态,由于sleep这种固定时间的方式产生的阻塞。

WAITING:阻塞,由于wait这种不固定时间的方式产生的阻塞。

BLOCKED:阻塞,由于锁竞争导致的阻塞。

线程安全(至关重要)

有些代码在单个线程环境下执行,完全正确。

但是如果让多个线程同时去执行,此时就可能会出现bug,此时就是线程不安全。如下所示

//线程安全
public class demo11 {
    private static int count = 0;

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> {
            //对count变量自增5w次
            for (int i = 0; i < 50000; i++) {
                count++;
            }
        });

        Thread t2 = new Thread(() -> {
            //对count变量自增5w次
            for (int i = 0; i < 50000; i++) {
                count++;
            }
        });
        t1.start();
        t2.start();

        //如果没有join,线程还没执行完就开始打印了
        t1.join();
        t2.join();

        //预期结果应该是10w,但是此时结果与10w相差甚远
        System.out.println("count:" + count);

    }
}

这种情况就是bug,只要实际结果和预期结果不符合,此时就一定是bug。

如果改为以下情况,就不会出错。就意味着,当t1正常运行时,t2是不会工作的,因此虽然写的是两个线程,但是同时只有一个线程在工作。

因此代码有没有问题,与“同时执行”关系很大。

t1.start();
t1.join();
        
t2.start();
t2.join();

为什么会出现这种情况呢?

count++这个操作,站在cpu的角度,本质上是分成三步进行的,cpu通过三个指令来实现的。

1)load 把数据从内存,读到cpu寄存器中

2)add 把寄存器中的数据+1

3)save 把寄存器中的数据,保存到内存中

如果是多个线程执行上述代码,由于线程之间的调度顺序是随机的,这会导致在有些调度顺序下,上述逻辑会发生错误。

此处这两个线程执行count++中间会产生无数种情况。因为也可能存在t1执行1次count++的时候,t2执行了2次3次等等,因此会有无数种情况。

结合上述讨论,我们意识到了在多线程程序中,最困难的一点线程的随机调度,使得两个线程执行逻辑的先后顺序,存在诸多可能。我们必须保证在所有可能的情况下,代码都是正确的。

在上述这些排列顺序中,有的执行结果是正确的,有的则有问题。

load操作是把内存中的count取出放入cpu核心中,add是让cpu核心中的count+1,save是把cpu核心中的结果存入内存中

//线程安全
public class demo11 {
    private static int count = 0;

    public static void main(String[] args) throws InterruptedException {
        Object locker = new Object();

        Thread t1 = new Thread(() -> {
            //对count变量自增5w次
            for (int i = 0; i < 50000; i++) {
                synchronized (locker) {
                    count++;
                }
            }
        });

        Thread t2 = new Thread(() -> {
            //对count变量自增5w次
            for (int i = 0; i < 50000; i++) {
                synchronized (locker){
                    count++;
                }
            }
        });
        t1.start();
        t2.start();

        t1.join();
        //如果没有join,线程还没执行完就开始打印了
        t2.join();

        //预期结果应该是10w,但是此时结果与10w相差甚远
        System.out.println("count:" + count);

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值