zl程序教程

您现在的位置是:首页 >  Java

当前栏目

JAVA 多线程——实现创建线程的五种写法

2023-02-18 16:37:41 时间

 ??前言 友友们大家好,我是你们的小王同学?? 今天给大家带来的是 JAVA 多线程——实现创建线程的五种写法 希望能给大家带来有用的知识 小王的主页:小王同学? 小王的gitee:小王同学? 小王的github:小王同学?

通过继承Thread类并实现run方法创建一个线程?

// 定义一个Thread类,相当于一个线程的模板
class MyThread01 extends Thread {
    // 重写run方法// run方法描述的是线程要执行的具体任务@Overridepublic void run() {
        System.out.println("hello, thread.");
    }
}
 
// 继承Thread类并重写run方法创建一个线程

public class Thread_demo01 {
    public static void main(String[] args) {
        // 实例化一个线程对象
        MyThread01 t = new MyThread01();
        // 真正的去申请系统线程,参与CPU调度
        t.start();
    }
}

通过实现Runnable接口,并实现run方法的方法创建一个线程?

// 创建一个Runnable的实现类,并实现run方法
// Runnable主要描述的是线程的任务
class MyRunnable01 implements Runnable {
    @Overridepublic void run() {
        System.out.println("hello, thread.");
    }
}
//通过继承Runnable接口并实现run方法

public class Thread_demo02 {
    public static void main(String[] args) {
        // 实例化Runnable对象
        MyRunnable01 runnable01 = new MyRunnable01();
        // 实例化线程对象并绑定任务
        Thread t = new Thread(runnable01);
        // 真正的去申请系统线程参与CPU调度
        t.start();
    }
}

通过Thread匿名内部类创建一个线程?

//使用匿名内部类,来创建Thread 子类
public class demo2 {
    public static void main(String[] args) {
        Thread t=new Thread(){ //创建一个Thread子类 同时实例化出一个对象
            @Override
            public void run() {
                while (true){
                    System.out.println("hello,thread");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        t.start();
    }
}

通过Runnable匿名内部类创建一个线程?

public class demo3 { //使用匿名内部类 实现Runnable接口的方法
    public static void main(String[] args) {
        Thread t=new Thread(new Runnable() {

            @Override
            public void run() {
                while (true){
                    System.out.println("hello Thread");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            }
        });
        t.start();
}
}

通过Lambda表达式的方式创建一个线程?

public class demo4 { //使用 lambda 表达式
    public static void main(String[] args) {
        Thread t=new Thread(()->{
            while (true){
                System.out.println("hello,Thread");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        });
        t.start();
    }
}