线程的启动和停止

启动

线程启动用start()方法,代码如下

public class MyThread implements Runnable {
    @Override
    public void run() {
        System.out.println("线程启动");
    }

    public static void main(String[] args) {
       Thread thread=new Thread(new MyThread());
        thread.start();//线程启动
    }
}

   start()方法的源码

public synchronized void start() {
    /**
     * This method is not invoked for the main method thread or "system"
     * group threads created/set up by the VM. Any new functionality added
     * to this method in the future may have to also be added to the VM.
     *
     * A zero status value corresponds to state "NEW".
     */
    if (threadStatus != 0)
        throw new IllegalThreadStateException();

    /* Notify the group that this thread is about to be started
     * so that it can be added to the group's list of threads
     * and the group's unstarted count can be decremented. */
    group.add(this);

    boolean started = false;
    try {
        start0();
        started = true;
    } finally {
        try {
            if (!started) {
                group.threadStartFailed(this);
            }
        } catch (Throwable ignore) {
            /* do nothing. If start0 threw a Throwable then
              it will be passed up the call stack */
        }
    }
}

private native void start0();//线程启动

   终止

 

1.stop

thread.stop();

  该方法已经过期,相当于liunx中的kill命令,强行关闭。不知道线程是否处理完,会出现一些不可预料的问题。

2.interrupt(中文的意思就是中断、阻塞的意思)

 使用它优雅的关闭,并不是直接关闭线程

Thread thread=new Thread(()-> {
    while (!Thread.currentThread().isInterrupted()){
        i++;
    }
    System.out.println(i);
});
thread.start();
TimeUnit.SECONDS.sleep(1);
thread.interrupt();//设置interrup标志为true
System.out.println(thread.isInterrupted());
Thread.interrupted();//对设置中断的线程设置复位
Thread thread=new Thread(()-> {
    while (true){
        boolean in=Thread.currentThread().isInterrupted();//isInterrupted()当前线程是否为中断状态
        if(in){
            System.out.println("before:"+in);
            Thread.interrupted();//设置复位
            System.out.println("after:"+Thread.currentThread().isInterrupted());
        }
    }
});
thread.start();
Thread.sleep(1000);
thread.interrupt();//线程中断

结果输出:

before:true
after:false

3.使用volatile

public class MyThread {
    private static int i = 0;
    volatile static boolean stop = false;

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(() -> {
            while (true) {
                i++;
                if (stop) {
                    break;
                }
            }
            System.out.println(i);
        });
        thread.start();
        Thread.sleep(1000);
        stop = true;
    }
}

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值