实现Runnable接口的形式创建线程

MyRunnable.java

package com.dym.juc;

/*
* 当线程类已经有父类了,就不能用Thread类的方式来创建线程
* 可以使用实现Runnable接口的方式去创建线程
* 1)定义类  实现Runnable接口
* */
public class MyRunnable implements Runnable{
    //2)重写Runnable接口中的抽象方法run()
    //  run()方法是子线程要执行的代码
    @Override
    public void run() {
        for (int i = 1; i <=100 ; i++) {
            System.out.println("sub thread -->"+i);
        }
    }
}

MyThreadTest3.java

package com.dym.juc;

/*
* 测试实现Runnable接口的形式来创建线程
*
* */
public class MyThreadTest3 {
    public static void main(String[] args) {
        //3)创建Runnable接口的实现类对象
        MyRunnable myRunnable = new MyRunnable();
        //4)创建线程对象
        Thread thread = new Thread(myRunnable);
        //5)开启线程
        thread.start();

        //当前是main线程
        for (int i = 1; i <=100 ; i++) {
            System.out.println("main -->"+i);
        }

        //有时调用Thread(Runnable)构造方法时,实参也会传递匿名内部类对象
        Thread thread2=new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 1; i <=100 ; i++) {
                    System.out.println("sub thread2222222222 -->"+i);
                }
            }
        });
        thread2.start();
    }
}

猜你喜欢

转载自blog.csdn.net/qq_39368007/article/details/115339733
今日推荐