zoukankan      html  css  js  c++  java
  • 创建多线程的方式

    创建多线程有三种方式来创建:
    1.继承Thread类
    2.实现Runnable接口
    3.使用Executor框架来创建线程池

    一.继承Thread类

    package com.test;
    
    /**
     * Created by admin on 2017/6/5 10:16.
     *
     */
    public class DemoThread extends Thread {
        private String name;
    
        DemoThread(String name) {
            this.name = name;
        }
    
        @Override
        public void run() {
            for (int i = 0; i < 40; i++) {
                System.out.println(name + ":" + i);
            }
        }
    
        public static void main(String[] args) {
            new DemoThread("线程1").start();
            new DemoThread("线程2").start();
            new DemoThread("线程3").start();
        }
    }

    二.实现Runnable接口

    package com.test;
    
    /**
     * Created by admin on 2017/6/5 10:16.
     */
    public class DemoThread implements Runnable {
    
        @Override
        public void run() {
            for (int i = 0; i < 40; i++) {
                System.out.println(Thread.currentThread().getName() + ":" + i);
            }
        }
    
        public static void main(String[] args) {
            DemoThread d1 = new DemoThread();
            Thread t1 = new Thread(d1, "线程1");
            Thread t2 = new Thread(d1, "线程2");
            Thread t3 = new Thread(d1, "线程3");
            t1.start();
            t2.start();
            t3.start();
        }
    }

     三.使用线程池创建

    package com.test;
    
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    
    /**
     * Created by admin on 2017/6/5 10:16.
     */
    public class DemoThread {
        public static void main(String[] args) {
            //固定大小的线程池,如果线程数量大于固定值,多的线程则会等待
            ExecutorService pool = Executors.newFixedThreadPool(3);
            pool.execute(() -> {
                for (int i = 0; i < 40; i++) {
                    System.out.println("线程1:" + i);
                }
            });
            pool.execute(() -> {
                for (int i = 0; i < 40; i++) {
                    System.out.println("线程2:" + i);
                }
            });
            pool.execute(() -> {
                for (int i = 0; i < 40; i++) {
                    System.out.println("线程3:" + i);
                }
            });
        }
    
    }
  • 相关阅读:
    CF1008D Pave the Parallelepiped
    Luogu P3324 [SDOI2015]星际战争
    Luogu P3157 [CQOI2011]动态逆序对
    CF1295E Permutation Separation
    位元算
    JavaScript 寻找数组中的第N大的元素
    JS常见的数组排序算法
    最新面试总结
    JavaScript BOM浏览器对象模型
    JavaScript DOM 事件
  • 原文地址:https://www.cnblogs.com/skyessay/p/6943777.html
Copyright © 2011-2022 走看看