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

    1 方式一:创建Thread的子类对象

    1-1 创建一个线程,继承 Thread,重写run方法

    public class MyThread extends Thread{
    
        public MyThread(String name){
            super(name);
        }
    
        @Override
        public void run(){
            for (int i = 0; i < 100; i++) {
                System.out.println(getName()+i);
            }
        }
    }
    

    1-2 测试类

    public class test2 {
        public static void main(String[] args) {
            MyThread t1 = new MyThread("线程1");
    
            for (int i = 0; i < 100; i++) {
                System.out.println("线程2"+i);
            }
            t1.start();
        }
    
    }
    

    2 方式二:实现 Runnable接口

    2-1 编写类,实现Runnable接口

    public class MyThread implements Runnable{
    
        @Override
        public void run(){
            for (int i = 0; i < 100; i++) {
                System.out.println(Thread.currentThread().getName()+i);
            }
        }
    }
    

    测试

    public class test2 {
        public static void main(String[] args) {
            MyThread myThread = new MyThread();
            Thread t1 = new Thread(myThread, "线程1");
            t1.start();
            for (int i = 0; i < 100; i++) {
                System.out.println("helloworld");
            }
        }
    
    }
    

    3 通过线程池创建多线程

    编写类,实现Runnable接口

    public class MyThread implements Runnable{
    
        @Override
        public void run(){
            for (int i = 0; i < 100; i++) {
                System.out.println(Thread.currentThread().getName()+i);
            }
        }
    }
    

    创建线程池

    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    
    public class test2 {
        public static void main(String[] args) {
            ExecutorService executorService = Executors.newFixedThreadPool(3);
            MyThread myThread = new MyThread();
            executorService.submit(myThread);
            executorService.submit(myThread);
            executorService.submit(myThread);
        }
    
    }
    
  • 相关阅读:
    华东交通大学2017年ACM双基程序设计大赛题解
    hdu2010(dfs+剪枝)
    欧拉函数phic以及超大数的快速幂
    想了一天的题目QAQ 毛线数列的最值
    记一下STL的一个题
    hdu1877进制转换
    hdu1002大数相加
    hdu1576逆元的一道水题
    Courses
    CodeForce-813B The Golden Age(数学+枚举)
  • 原文地址:https://www.cnblogs.com/hellosiyu/p/12482913.html
Copyright © 2011-2022 走看看