线程interrupt方法测试

测试Thread类

  • start()官方注释:
  • Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.
  • The result is that two threads are running concurrently:
    current thread (which returns from the call to the start method) and the other thread (which executes its run method).
    @Test
    public void testThread() throws ConfigException {
        Thread t1 = new Thread("t1") {
            public void run() {
                for (int i = 0; i < 10000; i++) {
                    System.out.println(Thread.currentThread() + "t1 run " + i);
                }
            }
        };
        Thread t2 = new Thread("t2") {
            public void run() {
                try {
                    for (int i = 0; i < 10000; i++) {
                        System.out.println(Thread.currentThread() + "t2 run " + i);
                        Thread.currentThread().sleep(3000L);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        System.out.println(Thread.currentThread() + "begin");
            t1.start();
            System.out.println(Thread.currentThread() + "t1 start interrupt.");
            t1.interrupt();
            t2.start();
            System.out.println(Thread.currentThread() + "t2 start interrupt.");
            t2.interrupt();

    }
  • 测试结果:
    • 测试类日志打印 Process finished with exit code 0 Thread[t1,5,main]t1 run 2234
    • 方法类打印日志:Thread[t1,5,main]t1 run 674
    • t1.start()替换为t1.run()之后,日志:Thread[main,5,main]t1 run 9999 Thread[main,5,main]t1 start interrupt.
  • 总结:
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值