004-创建多线程 方式二:实现Runnable接口


  方式2:实现Runnable接口
  步骤:
          A:自定义类MyRunnable实现Runnable接口
          B:重写run()方法
          C:创建MyRunnable类的对象
          D:创建Thread类的对象,并把C步骤的对象作为构造参数传递


public class MyRunnable implements Runnable {

    @Override
    public void run() {
        for (int x = 0; x < 100; x++) {
            
            // 由于实现接口的方式就不能直接使用Thread类的方法了,但是可以间接的使用
            System.out.println(Thread.currentThread().getName() + ":" + x);
        }

    }

}
public class MyRunnableTest {

    public static void main(String[] args) {

        // 创建MyRunnable类的对象 (Runnable接口的实现)
        MyRunnable my = new MyRunnable();

        // 创建Thread类的对象,并把C步骤的对象作为构造参数传递
        // 构造方式一:Thread(Runnable target)
        // Thread t1 = new Thread(my);
        // Thread t2 = new Thread(my);
        // t1.setName("詹姆斯");
        // t2.setName("小  毛");

        // 构造方式二: Thread(Runnable target, String name)
        // 创建两个线程,并修改线程名字
        Thread t1 = new Thread(my, "林青霞");
        Thread t2 = new Thread(my, "刘意");
        
        // 开启线程
        t1.start();
        t2.start();

    }

}


 

猜你喜欢

转载自www.cnblogs.com/penguin1024/p/11828104.html