多线程——继承Thread类实现一个多线程

继承Thread类实现一个多线程

 Thread类部分源码:

package java.lang;
//该类实现了Runnable接口
public class Thread implements Runnable {

    private volatile String  name;//线程名字
  
    //构造方法,用于创建一个实现Runnable接口的线程
    public Thread(Runnable target) {
        init(null, target, "Thread-" + nextThreadNum(), 0);
    }

    //构造方法,用于给一个线程命名
    public Thread(String name) {
        init(null, null, name, 0);
    }

    //构造方法,用于创建一个实现Runnable接口的线程,并给其命名
    public Thread(Runnable target, String name) {
        init(null, target, name, 0);
    }
    
    //启动线程的方法
    public synchronized void start() {
        if (threadStatus != 0)
            throw new IllegalThreadStateException();
        group.add(this);
        boolean started = false;
        try {
            start0();
            started = true;
        } finally {
            try {
                if (!started) {
                    group.threadStartFailed(this);
                }
            } catch (Throwable ignore) {
            }
        }
    }
    @Override
    public void run() {
        if (target != null) {
            target.run();
        }
    }
    //给一个线程命名
    public final synchronized void setName(String name) {
        checkAccess();
        if (name == null) {
            throw new NullPointerException("name cannot be null");
        }
        this.name = name;
        if (threadStatus != 0) {
            setNativeName(name);
        }
    }
    //获取线程的名字
    public final String getName() {
        return name;
    }
}

继承Thread的两个多线程类:

lic class MyThread1 extends Thread {
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println(Thread.currentThread().getName()+"启动线程...");
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
public class MyThread2 extends Thread {
    public MyThread2(String name) {
        super(name);
    }

    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println(super.getName() + ":启动线程...");
            // System.out.println(Thread.currentThread().getName() + ":启动线程...");
            try {
                sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

测试:

public class TestThread {
    public static void main(String[] args) {
        MyThread1 thread1 = new MyThread1();
        MyThread2 thread2 = new MyThread2("线程2");

        thread1.setName("线程1");
        
        thread1.start();
        thread2.start();
    }
}
结果:
线程2:启动线程...
线程1启动线程...
线程1启动线程...
线程1启动线程...
线程2:启动线程...
线程1启动线程...
线程2:启动线程...
线程1启动线程...
线程2:启动线程...
线程2:启动线程...

猜你喜欢

转载自www.cnblogs.com/whx20100101/p/9862469.html