线程的概念:线程是进程独立运行的子任务。
多线程是异步的。所以,Java代码启动线程的顺序不是线程的执行顺序。
通常实现线程有两种方式。
1 继承Thread类
2 实现Runnable接口。
下面对这两种方法进行验证。
继承Thread类实现
public class MyThread extends Thread{
@Override
public void run() {
super.run();
System.out.println("my thread");
}
}
实现Runnable接口实现
public class MyThreadRun implements Runnable{
@Override
public void run() {
System.out.println("my MyThreadRunnable");
}
}
主线程
public class Run {
public static void main(String[] args) {
//1 继承Thread类实现线程
MyThread myThread=new MyThread();
myThread.start();
//2 实现runable接口
MyThreadRun myThreadRun=new MyThreadRun();
Thread thread=new Thread(myThreadRun);
thread.start();
}
}
开启两个线程在控制台打印如下
my thread
my MyThreadRunnable
启动线程到此完毕,但是停止线程确没这么简单。停止线程在Java中并不像break语句那样干脆,在多线程开发的时候是很重要的技术点。
停止一个线程意味着在线程处理完成任务之前停掉正在做的操作,也就是放弃当前操作。停止一个线程可以使用、Thread.stop()方法,但最好不要用,虽然它确实可以
停止一个线程,但这个方法是不安全的,而且是已经被启用作废的。
Java中有下面三种方法可以终止正在运行的线程。
- 1)使用退出标志,使线程正常 退出,也就是当run方法完成后线程终止。
- 2)使用stop方法强行终止。但是不推荐使用。因为stop和suspend及resume方法一样,都是过期作废的方法,使用它们可能产生不可预料的后果。
- 3)使用interrupt方法中断线程。但是要记住,调用interrupt只是给当前线程打上一个停止的标记,而并非是停止一个线程。需要和return配合使用。
此处验证第三种方法。
public class MyThread extends Thread {
@Override
public void run() {
super.run();
while(true){
if(this.isInterrupted()){
System.out.println("停止了");
return;
}
System.out.println(System.currentTimeMillis());
}
}
}
public class Run {
public static void main(String[] args) throws InterruptedException {
MyThread thread=new MyThread();
thread.start();
Thread.sleep(1000);
thread.interrupt();
}
}
控制台输出
1533129685102
1533129685102
1533129685102
1533129685102
1533129685102
停止了
可以发现,停止线程并不是一个break,而是利用interrupt方法给线程打上终止的标记,此时,isInterrupted()方法值为true,进入if,并return。
this.interrupted() :测试当前线程是否已经中断。
this.isInterrupted():测试线程是否已经中断。