• 创建多线程的方式


    创建多线程有三种方式来创建:
    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);
                }
            });
        }
    
    }
  • 相关阅读:
    14.使用nodejs将规定格式的txt转化为json数据
    13.resize妙用(书上看到的)
    12.写了一个怪怪的边框
    11.一起来抄一个小小的提示菜单
    UI02-textfiled.按钮 uibutton
    UI01-UIview UIlable的属性
    OC9-内存管理
    OC8-属性 KVC是键值编码
    OC7-‍ 类目,延展 协议代理。
    OC6-block-函数指针
  • 原文地址:https://www.cnblogs.com/skyessay/p/6943777.html
Copyright © 2020-2023  润新知