【JAVA】线程创建和匿名内部类

前言

看多线程时,发现一些匿名内部类的东西,然后就来总结一下。

1.继承Thread类

在类上实现匿名内部类

public class Demo1 {
  public static void main(String[] args) {
    Thread t = new Thread(){
      @Override
      public void run() {
        System.out.println("This is the thread class");
      }
    };
    t.start();
  }
}

如果不用匿名内部类实现,则

public class Demo extends Thread {

  @Override
  public void run() {
    System.out.println("This is Thread class");
  }

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

 2.实现Runnable接口

在接口上实现匿名内部类

public class Demo2 {

  public static void main(String[] args) {
    Runnable r = new Runnable() {
      public void run() {
        System.out.println("this is Runnable interface");
      }
    };
    Thread t = new Thread(r);
    t.start();
  }
}

如果不用匿名内部类实现,则

public class Demo3 implements Runnable {

  public void run() {
    System.out.println("This is Rubanle interface");
  }

  public static void main(String[] args) {
    Demo3 demo3 = new Demo3();
    Thread t = new Thread(demo3);
    t.start();
  }
}

 3.获取有返回值的线程

使用Callable接口和FutureTask

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

public class Demo2 implements Callable<Integer>{

  public static void main(String[] args) throws Exception{
    Demo2 d = new Demo2();
    FutureTask<Integer> task = new FutureTask<Integer>(d);

    Thread t = new Thread(task);
    t.start();
    System.out.println("我先干点别的。。。");

    Integer result = task.get();
    System.out.println("线程执行的结果为:" + result);

  }

  public Integer call() throws Exception {
    System.out.println("正在进行紧张的计算");
    Thread.sleep(3000);
    return 1;
  }
}

猜你喜欢

转载自www.cnblogs.com/jianpanaq/p/10165992.html