• 如何创建多线程


    1.继承 Thread类,并重写run()方法:

    public class Thread001 extends Thread{
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName()+"我是子线程");
        }
    
        public static void main(String[] args) {
            System.out.println(Thread.currentThread().getName()+"我是主线程");
            new Thread001().start();
        }
    }

    2.实现Runnable接口,并重写run()方法:

    public class Thread002 implements Runnable{
        public void run() {
            System.out.println(Thread.currentThread().getName()+"我是子线程1");
        }
    
        public static void main(String[] args) {
            new Thread(new Thread002()).start();
        }
    }

    3.使用内部类:

    public class Thread0022{
        public static void main(String[] args) {
            //写法1
            new Thread(new Runnable() {
                public void run() {
                    System.out.println(Thread.currentThread().getName()+"我是子线程1");
                }
            }).start();
            //写法二:使用lambda表达式
            new Thread(() -> System.out.println(Thread.currentThread().getName()+"我是子线程2")).start();
        }
    }

    4.可以带返回结果的线程Callable:

    但是这种方式的话因为要等待子线程返回结果,所以你它的用时跟直接一个方法走没啥区别。

    public class MyCallback implements Callable<String> {
        @Override
        public String call() throws Exception {
            try{
                Thread.sleep(3000);
            }catch (Exception e){}
            return "子线程返回了!";
        }
    
        public static void main(String[] args) throws ExecutionException, InterruptedException {
            System.out.println("主线程开始了!");
            FutureTask<String> futureTask = new FutureTask<>(new MyCallback());
            new Thread(futureTask).start();
            System.out.println("这是---》》》"+futureTask.get());
            System.out.println("主线程结束了!");
        }
    }

    5.线程池:

    public class Thread003 {
        public static void main(String[] args) {
            ExecutorService executorService = Executors.newCachedThreadPool();
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println("我是"+Thread.currentThread().getName()+"线程池1");
                }
            });
            //写法2:使用lambda表达式
            executorService.execute(() -> System.out.println("我是"+Thread.currentThread().getName()+"线程池2"));
        }
    }
  • 相关阅读:
    结对作业评分
    Week6&7——第一次项目冲刺(Alpha版本)
    软工辅修团队项目选题参考
    Week5——团队选题&需求分析
    Week4——结对练习&团队作业1
    nginx与Apache的对比以及优缺点
    oracle数据库-错误编码大全
    spring MVC原理
    Java操作Memcached
    zookeeper应用场景-java
  • 原文地址:https://www.cnblogs.com/LinTianwen/p/13376646.html
Copyright © 2020-2023  润新知