天天看點

Java 多線程 之 Runnable

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();
        }

    }

}