多线程1-创建线程-Thread&Runnable

大纲:

  1. Thread创建线程。
  2. Runnable创建线程。
  3. 小结。

一、java创建线程--继承Thead类

创建一个类继承Thead类,并重写run方法。

class Test {
    public static void main(String[] args) {
        System.out.println("当前线程:"+Thread.currentThread());
        new TestThread().start();
        new TestThread().start();
    }

    static class TestThread extends Thread {
        @Override
        public void run() {
            System.out.println("当前线程:"+Thread.currentThread());
        }
    }
}

/**
运行结果: 当前线程:Thread[main,5,main] 当前线程:Thread[Thread-0,5,main] 当前线程:Thread[Thread-1,5,main] */

二、java创建线程--实现Runnable接口

创建一个类实现Runnable接口,并重写run方法。

class Test {
    public static void main(String[] args) {
        System.out.println("当前线程:"+Thread.currentThread());
        new Thread(new TestThread()).start();
        new Thread(new TestThread()).start();
    }

    static class TestThread implements Runnable {
        @Override
        public void run() {
            System.out.println("当前线程:"+Thread.currentThread());
        }
    }
}

/**
运行结果:
 当前线程:Thread[main,5,main]
 当前线程:Thread[Thread-0,5,main]
 当前线程:Thread[Thread-1,5,main]
 */

小结:

  1. 两种方式都在main主线程下面创建了Thread-0和Thread-1这2个子线程。
  2. run方法不需要我们手动调用,线程开启后自动调用。

猜你喜欢

转载自www.cnblogs.com/liuboyuan/p/9945652.html
今日推荐