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

  • 相关阅读:
    mysql性能优化
    java技术路线
    浅谈分布式事务
    java图片压缩
    centos6.8 固定IP
    Mybatis批量插入返回自增主键(转)
    MySQL创建用户的三种方法 (并授权)转
    MyBatis SQL xml处理小于号与大于号
    MySQL数据库引擎MyISAM和InnoDB的区别介绍
    Gson学习文档
  • 原文地址:https://www.cnblogs.com/webglcn/p/4468690.html
Copyright © 2011-2022 走看看