您现在的位置是:首页 > 文章详情

Java 多线程 之 Runnable

日期:2018-09-02点击:517

http://www.verejava.com/?id=16992909097867

package com.thread;

/**
 注意:
        1. 如果要启动一个线程必须调用,start()方法
        2. 线程同时运行其实是,CPU分配给每个线程一段时间来顺序执行每个线程
        3. 因为java是单继承的,所以为了提高可扩展性,一般使用第二种实现Runnable
           的方式
           
           概念上 可以理解为  他们 main  MyThread 是同时进行
 */
public class TestRunnable {
    
    public static void main(String[] args) {
        //实列话一个线程
        MyThread2 t = new MyThread2();
        Thread thread = new Thread(t, "汽车线程");
        thread.start();//启动线程, run() 会自动调用

        Thread thread2 = new Thread(t, "火车线程");
        thread2.start();//启动线程, run() 会自动调用

        try {
            for (int i = 0; i < 100; i++) {
                System.out.println(Thread.currentThread().getName() + i);
                Thread.sleep(1000);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

//Alt+Shit+S 可以找到父类的方法
class MyThread2 implements Runnable {

    @Override
    public void run() {
        try {
            for (int i = 0; i < 100; i++) {
                System.out.println(Thread.currentThread().getName() + i);
                Thread.sleep(1000);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

http://www.verejava.com/?id=16992909097867

原文链接:https://yq.aliyun.com/articles/632772
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章