【多线程入门系列一】线程的创建,启动与停止

2018-02-09  本文已影响11人  5d44bc28b93d
ceHJJ2KACQh.jpg

多线程入门系列(一) 线程的基本知识

线程的创建

  1. 继承Thread类
 public class MyThread  extends Thread{
  @Override
  public void run() {
      super.run();
      System.out.println("Hello MyThread");
  }
}
  1. 实现Runnable接口
public class MyRunnableThread implements Runnable {

  @Override
  public void run() {
      System.out.println("Hello MyRunnableThread");
  }
}
  1. 实现Callable接口
class MyCallable implements Callable<String>{

  @Override
  public String call() throws Exception {
      Thread.sleep(10000);
      return "回调成功";
  }
}

public class Main {


  public static void main(String[] args) {
      MyCallable myCallable = new MyCallable();
      FutureTask<String> futureTask1 = new FutureTask<String>(myCallable);
      ExecutorService executor = Executors.newFixedThreadPool(2);        // 创建线程池并返回ExecutorService实例
      executor.execute(futureTask1);
      while(true){
          if(futureTask1.isDone()){
              try {
                  System.out.println(futureTask1.get());
                  break;
              } catch (InterruptedException e) {
                  e.printStackTrace();
              } catch (ExecutionException e) {
                  e.printStackTrace();
              }
          }else{
              System.out.println("等待中。。。");
          }
      }
  }
  1. 总结对比

    • 使用继承的方式来开发多线程应用程序在设计上存在局限性。因为Java不支持多继承。而为了改变这一限制我们可以采用实现Runnable的方式。
    • Callable与其他两种的区别在于当线程执行完毕后可以接受返回值。

线程的启动

  1. start 方法

优雅的停止线程


        ```java
        public class MyThread extends Thread {
            @Override
            public void run() {
                super.run();
                while(true){
                }
            }
            }
        class Run {
            public static void main(String[] args) {
                MyThread thread = new MyThread();
                thread.start();
                thread.interrupt();
                System.out.println(thread.interrupted());
                System.out.println(thread.isInterrupted());
                Thread.currentThread().interrupt();
                System.out.println(
                    Thread.currentThread().isInterrupted()
                    );
                System.out.println(
                    Thread.currentThread().interrupted()
                    );
                System.out.println(
                    Thread.currentThread().interrupted()
                    );
            
            }
        
        ```
  * 前面两个输出分别为false,true,因为interrupted检测当前线程是否中断,而当前线程为main方法的主线程并且并未中断所以为false,而isInterrupted则检测线程是否中断,可以看出线程调用了interrupt方法确实是使其中断标志位为true,细心的可以发现如果在while循环里面加上打印输出,interrupt方法并没有真正的中断线程,仅仅的修改了标志位。
  * 后面三个输出分别为true true false ,最后一个输出为false是因为interrupted调用后重置了标志位。
    ```java
    public class MyThread extends Thread {
    @Override
    public void run() {
        super.run();
        try {
            for (int i = 0; i < 500000; i++) {
                System.out.println("运行中");

            }
            Thread.sleep(1000);
            System.out.println("end");
        } catch (InterruptedException e) {
            System.out.println("进入catch" + this.isInterrupted());
            e.printStackTrace();
        }
    }
     }

    class Run {
        public static void main(String[] args) {

            try {
                MyThread thread = new MyThread();
                thread.start();
                Thread.sleep(500);
                thread.interrupt();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }


        }
    }
    ```
上一篇 下一篇

猜你喜欢

热点阅读