码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2018-11-12 13:21:51      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:类继承   int   test   The   nts   开启   div   两种   运行   

大纲:

  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方法不需要我们手动调用,线程开启后自动调用。

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

标签:类继承   int   test   The   nts   开启   div   两种   运行   

原文地址:https://www.cnblogs.com/liuboyuan/p/9945652.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!