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

  • 相关阅读:
    Redis之面试题总结
    nginx入门,安装
    NGINX工作原理(2)
    Ngnx工作原理(1)
    Linux之常用脚本
    进程管理工具之supervisor[详解]
    PHP进阶书籍
    LVS、Nginx及HAProxy
    高级程序员与初级程序员差别在哪里?
    详解Wox
  • 原文地址:https://www.cnblogs.com/webglcn/p/4468690.html
Copyright © 2011-2022 走看看