windows操作系统拥有在同一时刻运行多个程序的能力,每一个程序又可以分为多个任务,每个任务被称为一个线程,线程之间有共享的数据。
Java实现多线程的方式主要有两种:
//第一种:实现Runnable接口,注入到Thread的构造函数中。
public class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("这是一个线程");
}
public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());//创建一个线程,注入Runnable的实现
thread.start();//start开启一个线程
}
}
//第二种:继承Thread类,重写run方法。
public class MyThread extends Thread{
@Override
public void run() {
System.out.println("这是一个线程");
}
public static void main(String[] args) {
Thread thread = new MyThread();
thread.start();
}
}
中断线程:
当线程的run方法执行完,或者出现了没有捕获的异常时,线程会被终止。
线程不可被强制终止,Interrupt方法可以请求终止线程。
void Interrupt:对线程调用interrupt方法时,线程的中断状态被置位。每一个线程都有这样一个Boolean标志,线程会随时检查这个标志,判断线程是否被中断。中断的线程上调用sleep会抛出InterruptedException。
如何判断线程的中断状态:调用Thread.currentThread方法可以获得当前的线程,然后调用isInterrupted方法。
static Thread currentThread():返回当前线程的Thread对象。
boolean inInterrupted():测试线程是否被终止。
线程请求了中断但是并不一定被终止,但可以选择如何响应中断。
public void run() {
System.out.println("这是一个线程");
interrupt();
while(Thread.currentThread().isInterrupted()==true){
//处理中断请求
System.out.println("线程请求中断");
return;
}
}
static boolean interrupted():测试线程是否被中断,然后将中断状态重置为false。