02 Java多线程及并发 runable、callable;理解interrupt中断;jvm信息如何查看;线程可以被中断吗?

1、Runable、Callable

  • 只有Thread代表线程,Runable仅代表一个任务,可以被任何线程执行的任务。
  • Runable不能有返回值,不能抛出checked exception。
  • Callable 可以有返回值,也能抛出异常。

2、Thread中断

  • 为什么线程中使用Thread.sleep等方法时,需要抛出InterruptedException
  • Thread.interrupt 唯一的用处就是取消一个耗时的操作。中断别的线程。
  • 允许线程A对线程B进行有限度的控制。
  • 线程可以选择不影响InterruptedException,但不推荐。
  • 除非你非常确定目标线程的中断特性,否则不要中断它。

Thread.interrupt 中断其它线程的示例

主线程中断Thread线程。

public static void main(String[] args) throws InterruptedException {
       Thread newThread = new Thread(() -> {
           try {
               Thread.sleep(1000);
           } catch (InterruptedException e) {
               System.err.println("Thread被中断了。");
               e.printStackTrace();
           }
       });
       newThread.start();
       //主线程睡500ms
       Thread.sleep(500);
       newThread.interrupt();//在主线程中 中断Thread线程

   }

输出:

Thread被中断了。
java.lang.InterruptedException
	at java.lang.Thread.sleep(Native Method)
	at java.lang.Thread.sleep(Thread.java:953)
	at com.lingyiwin.thread.ThreadInterrupt.lambda$main$0(ThreadInterrupt.java:13)
	at com.lingyiwin.thread.ThreadInterrupt$$Lambda$1/000000000000000000.run(Unknown Source)
	at java.lang.Thread.run(Thread.java:823)

1、任何线程都可以被中断吗?

不是的,取决于这个线程自己的决定。

public class ThreadInterrupt {
    public static void main(String[] args) throws InterruptedException {
        Thread newThread = new Thread(() -> {
            try {
                int i = 0;
                while (true){
                    doNothing();
                    i++;
                }
            } catch (InterruptedException e) {
                System.err.println("Thread被中断了。");
                e.printStackTrace();
            }
        });
        newThread.start();
        //主线程睡500ms
        Thread.sleep(500);
        newThread.interrupt();//在主线程中 中断Thread线程
    }

    public static void doNothing() throws InterruptedException{
        System.out.println("doNothing function....");
    }
}

输出:

doNothing function....
doNothing function....
doNothing function....
//........
doNothing function....
doNothing function....
doNothing function....

看看jvm干了什么.如下代码一直在执行循环。

"Thread-3" Id=28 RUNNABLE
        at com.lingyiwin.thread.ThreadInterrupt.lambda$main$0(ThreadInterrupt.java:15)
        at com.lingyiwin.thread.ThreadInterrupt$$Lambda$1/000000000000000000.run(Unknown Source)
        at java.lang.Thread.run(Thread.java:823)

2、中断只能发生在如下方法中吗?

==取决于线程自己的策略,JVM的阻塞方法都会正常响应。

3、如果没有能力处理中断,请重新设置中断标志位,使其它调用者知道该线程被中断了。

示例:

private static class T1 extends Thread {
        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                try {
                    TimeUnit.MICROSECONDS.sleep(500);
                } catch (InterruptedException e) {
                	//重新设置中断标志位。
                    Thread.currentThread().interrupt();
                    //e.printStackTrace();
                }
                System.out.println("T1");
            }
        }
    }

3、如何让线程一直等待

countDownLatch 这个类使一个线程等待其他线程各自执行完毕后再执行。

通过一个计数器来实现的,计数器的初始值是线程的数量。每当一个线程执行完毕后,计数器的值就-1,当计数器的值为0时,表示所有线程都执行完毕,然后在闭锁上等待的线程就可以恢复工作了。

调用await()方法的线程会被挂起,它会等待直到count值为0才继续执行.

示例:

public class CountDownLatchTest {

    public static void main(String[] args) {
        final CountDownLatch latch = new CountDownLatch(2);
        System.out.println("主线程开始执行…… ……");
        //第一个子线程执行
        ExecutorService es1 = Executors.newSingleThreadExecutor();
        es1.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(3000);
                    System.out.println("子线程:"+Thread.currentThread().getName()+"执行");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                latch.countDown();
            }
        });
        es1.shutdown();

        //第二个子线程执行
        ExecutorService es2 = Executors.newSingleThreadExecutor();
        es2.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("子线程:"+Thread.currentThread().getName()+"执行");
                latch.countDown();
            }
        });
        es2.shutdown();
        System.out.println("等待两个线程执行完毕…… ……");
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("两个子线程都执行完毕,继续执行主线程");
    }
}

输出:

主线程开始执行…… ……
等待两个线程执行完毕…… ……
子线程:pool-1-thread-1执行
子线程:pool-2-thread-1执行
两个子线程都执行完毕,继续执行主线程

Semaphore 也是一个线程同步的辅助类,可以维护当前访问自身的线程个数,并提供了同步机制。使用Semaphore可以控制同时访问资源的线程个数.

void acquire():从此信号量获取一个许可,在提供一个许可前一直将线程阻塞,否则线程被中断。
示例:

public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();

        //信号量,只允许 3个线程同时访问
        Semaphore semaphore = new Semaphore(3);

        for (int i = 0; i < 10; i++) {
            final long num = i;
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        //获取许可
                        semaphore.acquire();
                        //执行
                        System.out.println("Accessing: " + num);
                        Thread.sleep(new Random().nextInt(5000)); // 模拟随机执行时长
                        //释放
                        semaphore.release();
                        System.out.println("Release..." + num);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }

        executorService.shutdown();
    }

4、如何看JVM中的信息

使用 jps 和 jstack命令
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

EngineerForSoul

你的鼓励是我孜孜不倦的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值