java的多线程学习,第一记

实现多线程有三种方法

1,继承THread类

import com.sun.org.apache.xpath.internal.SourceTree;

public class test{

    //继承Thread类并重写run方法
    public static class MyThread extends Thread{
        @Override
        public void run(){
            System.out.println("I am a child thread");
        }
    }

    public static void main(String[] args) {
        //创建线程
        MyThread thread = new MyThread();
        //启动线程
        thread.start();
    }


}

2,实现Runable接口

public class test1{

    public static class RunableTask implements Runnable{
        private String param;

        @Override
        public void run(){
            System.out.println(param+"I am a child thread");
        }

        public RunableTask(String param){
            this.param = param;
        }

        
    }

    public static void main(String[] args) {
        RunableTask task1 = new RunableTask("21312");
        RunableTask task2 = new RunableTask("123123123");
        new Thread(task1).start();
        new Thread(task2).start();
    }

   

}
 

3,使用FutrueTask方法

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

public class test2{
    

    public static class CallerTask implements Callable<String>{

        @Override
        public String call()throws Exception{
            return "hello";
        }
    }

    public static void main(String[] args) {
        //create asynchronous task
        FutureTask<String> futureTask = new FutureTask<>(new CallerTask());
        //start thread
        new Thread(futureTask).start();
        try {
            //wait task excute 
            String result = futureTask.get();
            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 三种方式的对比优劣:

使用继承方式的好处是,在run()方法内获取当前线程直接使用this就可以了,无须使用Thread.currentThread()方法,不好的地方是Java不支持多线程,如果继承了Thread类,

那么就不能继承其他类了。另外任务与代码没有分离,当多个线程执行一样的任务时需

要多份任务代码,而Runable接口则没有这个限制。

如上面代码所示,两个线程共用一个task代码逻辑,如果需要,可以给RunableTask添加参数

进行任务区分。但是上面两种方式都有一个缺点,就是任务没有返回值。用FutureTask方式是有返回值的

原文地址:https://www.cnblogs.com/fuckingPangzi/p/10033526.html