多线程---2

1.多线程

  • 多线程执行时,并发并行的特性,及状态的转变
public class ThreadSeq {

    public static void main(String[] args) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("子线程执行");
            }
        },"子线程").start();
        System.out.println("main线程执行");
    }
}
  • main线程执行的:
    1. new Runnable
    2. new Thread 创建"子线程",申请系统创建一个线程,比较耗时
    3. start() 创建态——>就绪态
  • 并行并发执行
  • main线程在start()时处于运行态,继续执行打印语句,机率是非常大的,执行时间是非常快的。
  • 子线程创建比较耗时,系统调度也需要一定的时间
  • 整体看main线程和子线程同时并发并行并执行打印语句,最先执行的很大几率是main 线程中的打印语句。

2.Thread 基础api

2.1基础API

  • 当前线程:某个代码行所在的线程
static ThreadcurrentThread()返回对当前正在执行的线程对象的引用
static voidyield()线程让步,当前线程由运行态装变为运行态
static voidsleep(long millis)线程休眠:让当前线程休眠到指定时间(单位是毫秒)阻塞等待,时间到了继续执行
static intactiveCount()

2.2 增加运行速度

  • 多线程的优势:增加运行速度,但是创建线程也是耗费时间和资源的。
  • 如何确定线程数?
  • 总任务量恒定,系统可用资源恒定的情况下:
  • 线程创建是个比较耗时的操作,单个任务量比较小,还不如一个线程就完成,不用开启新线程来完成。
public class ThreadAdv {

    public static void main(String[] args) {
        //串行方式
        //循环10亿次,每次都++运算
        long start =System.nanoTime();
        for(int i =0;i<10;i++){
            loop();
            loop();
        }
        long end = System.nanoTime();
        System.out.printf("串行执行耗时:%s毫秒%n",(end-start)/1000/1000);

        //并行的方式:main线程,子线程同时执行loop方法
        //子线程执行完,main线程才能一直向下执行
        //使用activeCount ,要用DeBug
        long start2 = System.nanoTime();
        for(int i =0;i<10;i++){
            new Thread((new Runnable() {
                @Override
                public void run() {
                    loop();
                    loop();
                }
            })).start();
        }
        //当前main线程和main线程中创建的子线程,活跃线程数>1,main线程就一直让步
        while(Thread.activeCount()>1) Thread.yield();
        long end2=System.nanoTime();
        System.out.printf("并行执行耗时:%s毫秒%n",(end2-start2)/1000/1000);
    }
    private  static void loop(){
        int n =10_0000_0000;
        int m =0;
        for(int i =0;i<n;i++){
            m++;
        }
    }
}

2.3中断一个线程

2.3.1使用标志位

  • 使用标志位:可以实现在某种程度上的,在满足条件(中断线程的条件,如转账发现诈骗)情况下,中断线程存在的问题:
  • 如果线程处于阻塞状态(需要满足一定条件如sleep()休眠一定的时间,才能恢复),就无法快速的中断线程。
public class FlagStopThread {
	//使用标志位标识是否继续执行线程的中任务,true停止,false继续执行

    public static volatile boolean isStop = false;

    public static void main(String[] args) throws InterruptedException {
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("开始转账");
                try {
                    while(!isStop){
                        System.out.println("转账ing...");
                        Thread.sleep(10000);
                    }
                    System.out.println("停止转账");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        Thread.sleep(3*1000);
        //发现是诈骗犯,需要停止转账
        isStop=true;
    }
}

2.3.2基于Thread类本身的api来实现中断

  • Thread类中,保存有一个中断标志位,初始值=false(没有被中断)
voidinterrupt()
  • 某个线程的引用.interrupt()
  • 中断某个线程:
    1. 线程中断标志位=true
    2. 线程要不要中断,线程定义任务的代码自行决定。
    3. 如果线程处于阻塞状态(调用多线程api,显示抛出InterruptedException的方法)
  • 线程可以获取中断标志位,通过循环判断,来决定是否需要中断。
static booleaninterrupted()测试当前的线程是否中断
  • boolean isInterrupted=当前线程的中断标志位
  • 当前线程的中断标志位=false;重置标志位
booleanisInterrupted()测试这个线程是否被中断
  • return 当前线程的中断标志位
public class InterruptedResetFlag {

    public static void main(String[] args) {
//        text1();
        text2();
    }

    public static void text1(){
        Thread t =new Thread(new Runnable() {
            @Override
            public void run() {
                for(int i =0;i <10;i++){
                    System.out.println(Thread.currentThread().isInterrupted());
                }
            }
        });
        t.start();
        t.interrupt();
    }

    public static void text2(){
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i =0;i<10;i++) {
                    //i==0,打印true,重置标志位=false
                    System.out.println(Thread.interrupted());
                }
                //打印结果第一次为true,后面为false
            }
        });
        t.start();
        t.interrupt();//1.标志位=true
    }
}

2.4线程等待

voidjoin()等待这个线程死亡
voidjoin(long millis)
  • 线程引用对象.join()/线程引用对象.join(long)
  • 当前线程等待,直到满足…条件
  • 无参的方法,就是线程执行完毕;
  • 有参的放撒,是线程执行完毕和时间到达任意一个满足,满足以后,当前线程继续往下执行。
public class ThreadJoin {

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

    public static void text1() throws InterruptedException {
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println("t start");
                    Thread.sleep(3*1000);
                    System.out.println("t.end");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t.start();
        t.join();//main线程一直阻塞等待,知道t线程执行完毕
        System.out.println("main running...");
    }

    public static void text2() throws InterruptedException {
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("t run");
            }
        });
        t.start();
        t.join();//main线程一直阻塞等待,知道t线程执行完毕
        System.out.println("main running...");
    }
}

2.5守护线程

voidsetDaemon(boolean on)此线程标记为daemon线程或是用户线程
booleanisDaemon()测试这个线程是否为守护线程
  • new Thread默认的是用户线程
  • 线程引用对象.setDaemon(boolean),设置某个线程为守护线程(true),或用户线程(false)
  • java进程运行是通过main方法运行,会产生一个main线程,java进程需要至少一个用户线程存活,进程才不会结束
public class DaemonThread {

    public static void main(String[] args) {
        Thread t =new Thread(new Runnable() {
            @Override
            public void run() {
                while(true){}
            }
        });
        t.setDaemon(true);//注释就是t线程一直运行
        //不只是就是设置t为守护线程,java进程的结束就不考虑该线程了
        t.start();
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值