zoukankan      html  css  js  c++  java
  • 线程入门-创建线程

    创建线程有2种方式,继承Thread类 和 实现Runnable接口的方式
    public class ThreadTest {
        public static void main(String[] args) {
            System.out.println("main-start...");
            MyThread t = new MyThread();
            t.start(); // 启动新线程t1
            Thread t2 = new Thread(new MyRunnable());
            t2.start(); // 启动新线程t2
            System.out.println("main-end...");
        }
    }
    
    /**
     * 继承 Thread 方式
     */
    class MyThread extends Thread {
        @Override
        public void run() {
            System.out.println("by Thread start new thread!");
        }
    }
    
    /**
     * 实现Runnable接口方式
     */
    class MyRunnable implements Runnable {
        @Override
        public void run() {
            System.out.println("by Runnable start new thread!");
        }
    }

    运行多次控制台输出:

    main-start...
    by Thread start new thread!
    main-end...
    by Runnable start new thread!

    或者

    main-start...
    by Thread start new thread!
    by Runnable start new thread!
    main-end...

    结果会有不同

  • 相关阅读:
    图论
    数学
    P2222 外婆婆~
    P2083 找人
    P1215 [USACO1.4]母亲的牛奶 Mother's Milk
    New Rap
    P2298 Mzc和男家丁的游戏
    P2040 打开所有的灯
    P1135 奇怪的电梯
    UVA10474 Where is the Marble?
  • 原文地址:https://www.cnblogs.com/wanjun-top/p/12817965.html
Copyright © 2011-2022 走看看