【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;
  }
}

 

4.线程定时任务

使用Timer类另起一个线程:

timer.schedule(TimerTask task, long delay, long period),第一个参数表示任务,第二个参数表示延迟时间,即启动main方法后多久才会调用run方法的时间;第三个参数表示每隔多久重复执行run()方法,用等差数列表示,delay表示首项, period表示公差。

import java.util.Timer;
import java.util.TimerTask;

public class Demo1 {

  public static void main(String[] args) {
    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
      @Override
      public void run() {
        System.out.println("start to run");
      }
    },10000,1000);
    System.out.println("main thread");
  }
}

 5.线程池

关于线程池的知识,暂不讲解,只是做个demo。

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Demo2 {

  public static void main(String[] args) {
    ExecutorService executorService = Executors.newCachedThreadPool();
    for(int i =0;i<=100;i++){
      executorService.execute(new Runnable(){
        public void run() {
          System.out.println(Thread.currentThread().getName() + "正在执行");
        }
      });
    }
  }
Ride the wave as long as it will take you.
原文地址:https://www.cnblogs.com/jianpanaq/p/10165992.html