Home | 简体中文 | 繁体中文 | 杂文 | Github | 知乎专栏 | Facebook | Linkedin | Youtube | 打赏(Donations) | About
知乎专栏

7.3. 继承 Thread 类实现多线程

		
package cn.netkiller.ipo.test;

public class MyThread extends Thread {

	private String name;

	public MyThread(String name) {
		super();
		this.name = name;
	}

	public void run() {
		for (int i = 0; i < 10; i++) {
			System.out.println("Thread:" + this.name + ",i=" + i);
		}
	}

	public static void main(String[] args) {
		MyThread mt1 = new MyThread("A");
		MyThread mt2 = new MyThread("B");
		mt1.start();
		mt2.start();
	}
}
		
		

7.3.1. 设置线程名称

			

    public static void setThreadName1() {
        new Thread("thread-name-1") {
            public void run() {
                try {
                    Thread.sleep(1000 * 15);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("threadName1: " + this.getName());

            }
        }.start();
    }

    public static void setThreadName2() {
        new Thread() {
            @SneakyThrows
            public void run() {
                this.setName("thread-name-2");
                Thread.sleep(1000 * 15);
                System.out.println("threadName2: " + this.getName());

            }
        }.start();
    }

    public static void setThreadName3() {
        Thread thread = new Thread() {
            public void run() {
                try {
                    Thread.sleep(1000 * 15);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("threadName3: " + this.getName());

            }
        };

        thread.setName("thread-name-3");
        thread.start();
    }

    public static void setThreadName4() {
        new Thread("测试线程-1") {
            public void run() {
                try {
                    Thread.sleep(1000 * 15);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("threadName1: " + this.getName());

            }
        }.start();
    }			
			
			

			
public class MyThread extends Thread {
    public MyThread(){

    }
    public MyThread(String name){
        super(name);
    }
    @Override
    public void run(){
        System.out.println(Thread.currentThread().getName());
    }
}

public class DemoThreadName {

    public static void main(String[] args) {

        MyThread mt = new MyThread();
        mt.setName("景峰");
        mt.start();

        new MyThread("netkiller").start();

    }
}