java线程

189 阅读2分钟

java创建线程的几种方式

一:继承Thread类

public static class Thread1 extends Thread{
    public void run(){
        System.out.println("创建线程的第一种方式"+Thread.currentThread().getName());
    }
}

测试代码如下

public  static void main(String[] args){
    System.out.println("main方法-----start");
    Thread thread1 = new Thread1();
    thread1.start();
    System.out.println("main方法-----stop");

}

测试结果 image.png

二:实现Runnable接口

public static class Thread2 implements Runnable{
    @Override
    public void run() {
        System.out.println("创建线程的第二种方式"+Thread.currentThread().getName());
    }
}

测试

public  static void main(String[] args){
    System.out.println("main方法-----start");
    Thread2 thread2=new Thread2();
    new Thread(thread2).start();
    System.out.println("main方法-----stop");

}

测试结果 image.png

三:实现Callable接口结合FutureTask带返回值

public static class callable implements Callable {
    @Override
    public Object call() throws Exception {
        int i=10/5;
        System.out.println("创建线程的第三种方式,实现Callable,"+"返回值是:"+i);
        return i;
    }
}

测试

public  static void main(String[] args){
    System.out.println("main方法-----start");
    FutureTask task=new FutureTask(new callable());
    new Thread(task).start();
    System.out.println("main方法-----stop");

}

测试结果 image.png

四:定时器(java.util.Timer)

public  static void main(String[] args){
    System.out.println("main方法-----start");
   Timer timer=new Timer();
   timer.schedule(new TimerTask(){
       @Override
       public void run() {
           System.out.println("实现多线程第四种方式---定时器");
       }
   },10,100);
    System.out.println("main方法-----stop");

}

测试结果 image.png 总结:Timer实例可以调度多任务,它是线程安全的。 当Timer的构造器被调用时,它创建了一个线程,这个线程可以用来调度任务。Timer有不可控的缺点,当任务未执行完毕或我们每次想执行不同任务时候,实现起来比较麻烦,可以考虑使用作业调度框架,比如quartz等

五:线程池

编写一个工具类读取properties文件参数

public static Object getParamValue(String key){
    InputStream is=getParamValueFromproperties.class.getClassLoader().getResourceAsStream("application.properties");
    BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(is));
    Properties properties=new Properties();
    try {
        properties.load(bufferedReader);
        return properties.get(key);
    }catch (IOException e){
        e.printStackTrace();
    }
    return null;
}

配置文件如下: image.png

public  static void main(String[] args){
    String key="threadpoolMaxNum";
    String paramValue =(String)getParamValueFromproperties.getParamValue(key);
    int num=Integer.parseInt(paramValue);
    System.out.println("从配置文件读取到的线程池线程数是"+num);
    ExecutorService threadpool=Executors.newFixedThreadPool(num);
    for(int i=0;i<5;i++){
        threadpool.execute(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName()+"is Running");
            }
        });
    }
    //threadpool.shutdown();
}

测试结果 image.png

总结:在实际生产环境下,我们一般都会使用线程池的方式,达到资源可控,系统稳定的设计,这个系统一般都会维护一到两个线程池,来统一调度线程资源。