程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长


+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

2023-05(1)

Java多线程创建的几种方式

发布于2020-11-19 20:07     阅读(465)     评论(0)     点赞(12)     收藏(0)


public class Run implements Runnable{
    @Override
    public void run() {
        String threadName = Thread.currentThread().getName();
        System.out.println("当前线程 "+threadName);
    }

    public static void main(String[] args) {
        new Thread(new Run()).start();
    }
}
public class Run extends Thread{
    @Override
    public void run() {
        String threadName = Thread.currentThread().getName();
        System.out.println("当前线程 "+threadName);
    }
    public static void main(String[] args) {
        new Thread(new com.kongdechang.stu.Run()).start();
    }
}
public class Run {
    public static void main(String[] args) {
        new Thread(()->{
            String threadName = Thread.currentThread().getName();
            System.out.println("当前线程 "+threadName);
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                String threadName = Thread.currentThread().getName();
                System.out.println("当前线程 "+threadName);
            }
        });
    }
}
public class Run implements Callable<String> {
    @Override
    public String call() throws Exception {
        String threadName = Thread.currentThread().getName();
        System.out.println("当前线程 "+threadName);
        return threadName;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Callable<String> callable = ()->{
            String threadName = Thread.currentThread().getName();
            System.out.println("当前线程 "+threadName);
            return threadName;
        };
        //获取线程池,执行线程数量
        ExecutorService es = Executors.newFixedThreadPool(2);
        //提交线程任务
        es.submit(new Run());
        es.submit(new Run());
        es.submit(new Run());
        es.submit(callable);
        // 接收返回值
        Future<String> future = es.submit(callable);
        //关闭线程池
        es.shutdown();
        System.out.println(future.get());
    }
}

原文链接:https://blog.csdn.net/by2233/article/details/109748984



所属网站分类: 技术文章 > 博客

作者:小胖子爱java

链接:http://www.javaheidong.com/blog/article/792/36e48be82fbe0f634622/

来源:java黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

12 0
收藏该文
已收藏

评论内容:(最多支持255个字符)