创建和运行线程

直接使用Thead

public class Main {
    public static void main(String []args){
        Thread t = new Thread(){
            @Override
            public void run(){
                //do something
            }
        };
        //start the thread
        t.start();
    }
}

使用Runnable配合Thread

此方法可以将线程任务分离

  • Thread表示线程
  • Runnable表示可运行的任务
public class Main {
    public static void main(String []args){
       Runnable runnable = new Runnable() {
           @Override
           public void run() {
               //do something
           }
       };

       //give task and thread name in param  
        Thread t = new Thread(runnable,"t1");
        t.start();
    }
} 

Java8以后可以用Lambda表达式创建Runnable

//create task case
//do something after the '->'
Runnable runnable = () -> {System.out.println(1);};
//first param is task case and second is thread name
Thread t = new Thread(runnable,"t1");
t.start();

Thread与Runnable的关系

  • Thread是将线程与任务合并在了一起,创建创建线程的时候必须指定好任务
  • Runnable将线程与任务分离,可以先创建线程,需要时再创建任务
  • Runnable更容易与线程池等高级API配合
  • Runnable让任务脱离了Thread的继承体系,更加灵活

FutureTask配合Thread

FutureTask能够接收Callable类型的参数,用来处理有返回结果的情况

public class Main {
    public static void main(String []args) throws ExecutionException, InterruptedException {

        FutureTask<Integer> task = new FutureTask<>(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                //do something
                return 100;
            }
        });

        Thread t = new Thread(task);
        t.start();
        //在get()方法获取到值之前主线程是阻塞的
        System.out.println(task.get());
    }
}

输出

100

观察多线程运行


public class Main {
    public static void main(String []args) throws ExecutionException, InterruptedException {
        new Thread(()->{
            while(true){
                System.out.println("t1");
            }
        },"t1").start();

        new Thread(()->{
            while(true){
                System.out.println("t2");
            }
        },"t2").start();
    }
}

观察到t1和t2交替输出,由此可推出系统调用方式(不同系统略有不同)