线程系列一、线程的创建与停止

1、通过继承Thread类

public static class MThread extends Thread{

    @Override
    public void run() {
        System.out.println(this.getName() + " start");
    }
}

public static void main(String[] args){
    new MThread().start();
}

2、通过实现Runnable接口实现

public static class MRunnable implements Runnable {

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() +" start");
    }
}

public static void main(String[] args){
    new Thread(new MRunnable()).start();
}

3、创建可抛异常且有返回值的线程任务

public static class MCallAble implements Callable {
    @Override
    public String call() throws Exception {
        return Thread.currentThread().getName() + " 测试";
    }
}

public static void main(String[] args) throws ExecutionException, InterruptedException {
    FutureTask task = new FutureTask<>(new MCallAble());
    Thread thread = new Thread(task);
    thread.start();
    System.out.println(task.get());
}

解释:

1、FutureTask的继承类图

因为FutureTask最终实现的是Runnable接口,因此FutureTask可以直接放在Thread中执行。

2、Callable接口

Callable接口允许我们在线程执行的时候有返回值,以及抛出异常!


4、线程的停止

①Thread类中的3个停止方法:

public void interrupt()
public static boolean interrupted()
public boolean isInterrupted()

②三者区别:

public void interrupt()

将线程标记为中断

public boolean isInterrupted() {
    return isInterrupted(false);
}

返回线程当前的中断状态,不清除线程的中断标记

public static boolean interrupted() {
    return currentThread().isInterrupted(true);
}

返回线程当前的中断状态,并清除线程的中断标记

interrupted() 与 isInterrupted() 本质都是调用了 native的 isInterrupted()。interrupted()清除了标记, isInterrupted()不清楚标记。

③中断示例代码

static class Mclass implements Runnable {
    @Override
    public void run() {
        while (!Thread.interrupted()) {
            System.out.println(Thread.currentThread().getName() + " start ");
        }
    }
}

public static void main(String[] args) {
    Thread thread1 = new Thread(new Mclass());
    Thread thread2 = new Thread(new Mclass());
    thread1.start();
    thread2.start();
    thread1.interrupt();
}

你可能感兴趣的:(java)