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

    }
}

			
			

7.3.2. 判断线程是否存活

			
package cn.netkiller.test;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

@Data
@Slf4j
public class Test {

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(() -> {
            try {
                Thread.sleep(1000); // 模拟任务执行
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        System.out.println("启动前是否存活: " + thread.isAlive()); // false (NEW)
        thread.start();
        System.out.println("启动后是否存活: " + thread.isAlive()); // true (RUNNABLE)

        Thread.sleep(500);
        System.out.println("运行中是否存活: " + thread.isAlive()); // true (TIMED_WAITING)

        thread.join(); // 等待线程结束
        System.out.println("结束后是否存活: " + thread.isAlive()); // false (TERMINATED)

        Thread thread1 = new Thread();
        System.out.println("启动前是否存活: " + thread1.isAlive()); // false 
    }

}			
			
			

7.3.3. 获取线程状态

			
package cn.netkiller.test;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

@Data
@Slf4j
public class Test {

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(() -> {
            try {
                Thread.sleep(1000); // TIMED_WAITING
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        System.out.println(thread.getState()); // NEW (before start)
        thread.start();
        System.out.println(thread.getState()); // RUNNABLE (after start)

        Thread.sleep(100);
        System.out.println(thread.getState()); // TIMED_WAITING (sleeping)

        thread.join();
        System.out.println(thread.getState()); // TERMINATED (after completion)
    }

}			
			
			

7.3.4. 安装终止一个线程

			
public class SafeInterrupted {
    public static void main(String[] args) throws InterruptedException {
        Thread worker = new Thread(() -> {
            // 定期检查中断状态
            while (!Thread.currentThread().isInterrupted()) {
                try {// 业余草
                    doWork();
                } catch (InterruptedException e) {
                    // 收到中断信号,清理资源后退出
                    System.out.println("收到中断信号,准备退出...");
                    cleanup();
                    break; // 或 return
                }
            }
        });
        
        worker.start();
        Thread.sleep(1000);
        worker.interrupt(); // 优雅地请求停止
    }
}			
			
			

volatile 标志位方式(推荐)

			
public class VolatileExample {
    private volatile boolean running = true;

    public void stop() {
        running = false;
    }
    
    public void run() {
        while (running) {
            doWork();
        }
        cleanup();
    }
}