Java教程

多线程

本文主要是介绍多线程,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1、创建多线程

1.1、继承Thread类

package demo;

/**
 * @description: demo01
 * @author: liuyang
 * @create: 2021-08-24 21:40
 */
public class Demo01 extends Thread {
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName());
    }

    public static void main(String[] args) {
        Demo01 myThread = new Demo01();
        myThread.setName("my-thread-test");
        myThread.start();
    }
}

1.2、实现Runnable接口

package demo;

/**
 * @description: demo02
 * @author: liuyang
 * @create: 2021-08-24 21:53
 */
public class Demo02 implements Runnable {
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName());
    }

    public static void main(String[] args) {
        // 方式1
        Thread myThread1 = new Thread(new Demo02());
        myThread1.setName("myThread1");
        myThread1.start();
        // 方式2-匿名内部类
        Thread myThread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName());
            }
        });
        myThread2.setName("myThread2");
        myThread2.start();
        // 方式3--函数式编程
        Thread myThread3 = new Thread(() -> {
            System.out.println(Thread.currentThread().getName());
        });
        myThread3.setName("myThread3");
        myThread3.start();
    }
}

 

这篇关于多线程的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!