Runnable的多种写法

Runnable的几种写法:

创建个类

public class MyRunnable implements Runnable {


    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println("Runnable线程:" + i);
        }
    }
}

以下包含多种匿名写法,仅供记录

public class MyMain {

    public static void main(String[] args) {

        //Runnable实现方法第一种
        Runnable target = new MyRunnable();
        new Thread(target).start();

        //第二种方法
        Runnable target1 = new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 5; i++) {
                    System.out.println("t1线程:" + i);
                }
            }
        };
        new Thread(target1).start();

        //第三种写法
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 5; i++) {
                    System.out.println("t2线程:" + i);
                }
            }
        }).start();

        //第四种学法
        new Thread(() ->{
            for (int i = 0; i < 5; i++) {
                System.out.println("t3线程:" + i);
            }
        }).start();


        for (int i = 0; i < 5; i++) {
            System.out.println("main线程:" + i);
        }

    }


}

 

posted @ 2024-10-30 16:39  多多指教~  阅读(1)  评论(0编辑  收藏  举报