2026/2/5 15:15:23
网站建设
项目流程
做儿童网站赚钱吗,国外室内设计专业大学排名,wordpress注册简化,seo运营是做什么的一、Thread的常见构造方法方法说明Thread()这会创建一个默认的线程对象#xff0c;没有指定要执行的任务Thread(Runnable target)通过传入一个 Runnable 接口的实现类来指定线程要执行的任务Thread(String name)创建线程并指定线程名称#xff0c;便于调试和日志记录Thread(R…一、Thread的常见构造方法方法说明Thread()这会创建一个默认的线程对象没有指定要执行的任务Thread(Runnable target)通过传入一个 Runnable 接口的实现类来指定线程要执行的任务Thread(String name)创建线程并指定线程名称便于调试和日志记录Thread(Runnable target,String name)同时指定任务和名称示例// 无参构造 Thread thread1 new Thread(); // 带 Runnable Runnable task () - System.out.println(Hello from thread); Thread thread2 new Thread(task); // 带名称 Thread thread3 new Thread(MyThread); // 带 Runnable 和名称 Thread thread4 new Thread(task, MyTaskThread);二、Thread的几种常见属性属性获取方法线程名称getName()线程优先级getPriority()守护线程标志isDeamo()线程IDgetId()线程状态getState()示例Thread thread new Thread(); System.out.println(Name: thread.getName()); // Thread-0 System.out.println(Priority: thread.getPriority()); // 5 System.out.println(Is Daemon: thread.isDaemon()); // false System.out.println(ID: thread.getId()); // 例如 12 System.out.println(State: thread.getState()); // NEW三、启动一个线程-start()要启动一个线程不能直接调用 run() 方法那样只是普通方法调用不会开启新线程而是要调用 start() 方法。start() 会通知 JVM 创建一个新线程并调用 run() 方法。public void start()启动线程。一旦调用线程进入 RUNNABLE 状态。注意一个线程只能调用一次 start()多次调用会抛出 IllegalThreadStateException。示例Thread thread new Thread(() - { System.out.println(Thread is running); }); thread.start(); // 启动线程四、中断一个线程方法说明public void interrupt()向线程发送中断信号设置中断标志public boolean isInterrupted()检查中断标志不清除public static boolean interrupted()检查并清除中断标志示例Thread thread new Thread(() - { while (!Thread.interrupted()) { System.out.println(Working...); } System.out.println(Interrupted!); }); thread.start(); // 稍后中断 thread.interrupt();五、等待一个线程-join()方法说明public void join()无限等待直到目标线程结束public void join(long millis)等待指定毫秒如果超时则继续public void join(long millis, int nanos)更精确的超时等待示例Thread thread new Thread(() - { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread finished); }); thread.start(); try { thread.join(); // 主线程等待 thread 完成 } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Main thread continues);六、获取当前线程引用方法说明public static Thread currentThread()返回当前线程的 Thread 对象示例public class Main { public static void main(String[] args) { Thread current Thread.currentThread(); System.out.println(Current thread: current.getName()); // main new Thread(() - { Thread inner Thread.currentThread(); System.out.println(Inner thread: inner.getName()); // Thread-0 }).start(); } }七、休眠当前线程方法说明public static void sleep(long millis)休眠指定毫秒public static void sleep(long millis, int nanos)更精确的休眠示例try { Thread.sleep(1000); // 休眠 1 秒 } catch (InterruptedException e) { // 处理中断 Thread.currentThread().interrupt(); // 重新设置中断标志 } System.out.println(Woke up!);