启动
线程启动用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; } }