Java多线程-继承Thread类,示例

 继承Thread类,调用start方法启动线程。

示例,

public class ThreadTest extends Thread {
    public ThreadTest(String name){
        super(name);
    }


    @Override
    public void run() {
        for (int i = 0; i<5 ; i++){
            System.out.println("Thread-"+Thread.currentThread().getName()+": "+i);
            try {
                Thread.sleep(Math.round(Math.random()*1000));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

    public static void main(String[] args){
        ThreadTest threadTest1 = new ThreadTest("Thread-1");
        threadTest1.start();

        ThreadTest threadTest2 = new ThreadTest("Thread-2");
        threadTest2.start();
    }
}

执行结果


Thread-Thread-2: 0
Thread-Thread-1: 0
Thread-Thread-2: 1
Thread-Thread-2: 2
Thread-Thread-1: 1
Thread-Thread-2: 3
Thread-Thread-1: 2
Thread-Thread-2: 4
Thread-Thread-1: 3
Thread-Thread-1: 4


 

你可能感兴趣的:(Java多线程-继承Thread类,示例)