zoukankan      html  css  js  c++  java
  • Java Thread and runnable

    java中可有两种方式实现多线程,

    一种是继承Thread类,(Thread本身实现了Runnable接口,就是说需要写void run 方法,来执行相关操作)

    一种是实现Runnable接口

    start, 和主线程一起执行,执行的顺序不确定

    join,线程们 先执行,当所有的子线程执行完毕后,主线程才执行操作(文章最下面的例子)

    // 1 Provide a Runnable object, the Thread class itself implements Runnable
    //~~~ 1.1
    Thread t1 = new Thread(new Runnable() {
        @Override
        public void run() {
            output("t1");
        }
    });
    t1.start();

    //~~~ 1.2 is more general
    public class HelloRunnable implements Runnable {
        public void run() {
            System.out.println("Hello from a thread!");
        }
    }
    (new Thread(new HelloRunnable())).start();

    // 2 Subclass Thread (in simple applications)  The Thread class itself implements Runnable
    public class HelloThread extends Thread {
        public void run() {
            System.out.println("Hello from a thread!");
        }
    }
     (new HelloThread()).start();

    // thread.join
    t1.start()
    t2.start()
    outputresult // 如果想要等到 两个线程t1, t2 都执行完成,再通过outputresult,在主线程输出结果,需要t1.join(), t2.join()

    t1.start()
    t2.start()
    t1.join()
    t2.join()
    outputresult

  • 相关阅读:
    HDU 1584 蜘蛛牌(DFS)
    HDU 1800 Flying to the Mars(贪心)
    zsh: command not found: java (xxx)
    Deepin20安装Mysql8
    Deepin全局菜单
    Ubuntu PPA 解读
    Node安装与配置
    Windows安装配置Maven
    idea 安装 Vue 插件没有Vue component选项
    Linux桌面系统创建应用程序快捷方式
  • 原文地址:https://www.cnblogs.com/webglcn/p/4468690.html
Copyright © 2011-2022 走看看