美文网首页
Java 线程

Java 线程

作者: 黑白_a9aa | 来源:发表于2019-05-08 09:25 被阅读0次

中断

  • 通过Thread类中的interrupt()方法,给出中断信号,结束当前线程
  • 通过ThreadGroup类中的interrupt()方法,给出中断信号,结束一组线程
    如果线程处于阻塞状态,会抛出InterruptedException

Thread中的interrupt()方法示例代码

package test;

import java.util.logging.Logger;

public class Test {
    private static final Logger log = Logger.getLogger(Test.class.getName());
    
    public static void main(String[] args) {
        Thread t = new Test().startThread("[Sub Thread]");
        try {
            t.sleep(30);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        
        log.info("thread " + Thread.currentThread().getName() + " send interrupt flag.");
        
        t.interrupt();
    }
    
    public Thread startThread(String tname) {
        Thread t = new Thread(new Runnable() {

            @Override
            public void run() {
                int sum = 0;
                int i = 0;
                log.info("thread " + Thread.currentThread().getName() + " i is " + i);
                log.info("thread " + Thread.currentThread().getName() + " sum is " + sum);
                while(!Thread.currentThread().isInterrupted()) {
                    log.info("thread " + Thread.currentThread().getName() + " is running.");
                    while(sum<i*1000) {
                        sum++;
                    }
                    
                    i++;
                    if(i > 100) {
                        log.info("thread " + Thread.currentThread().getName() + " is finished.");
                        break;
                    }
                }
                log.info("thread " + Thread.currentThread().getName() + " is stopped.");
                log.info("thread " + Thread.currentThread().getName() + " i is " + i);
                log.info("thread " + Thread.currentThread().getName() + " sum is " + sum);
            }
            
        }, tname);
        t.start();
        return t;
    }
    
}

相关文章

网友评论

      本文标题:Java 线程

      本文链接:https://www.haomeiwen.com/subject/jompoqtx.html