在Java中,Thread类是用来表示线程的类,它是并发编程的基础。以下是Thread类的一些常用方法及其使用示例:
public Thread(): 创建一个新的线程对象。
Thread t1 = new Thread();
public Thread(Runnable target): 使用Runnable对象创建一个新的线程。
Runnable r = () -> System.out.println("Hello from a thread!");
Thread t2 = new Thread(r);
public Thread(String name): 创建一个具有指定名称的新线程。
Thread t3 = new Thread("MyThread");
public Thread(Runnable target, String name): 使用Runnable对象创建一个新的线程,并指定名称。
Runnable r = () -> System.out.println(Thread.currentThread().getName());
Thread t4 = new Thread(r, "NamedThread");
public void start(): 导致此线程开始执行; Java虚拟机调用此线程的run方法。
t1.start();
t2.start();
public void run(): 此线程要执行的任务。
Thread t5 = new Thread(() -> {
// Your code here
});
t5.start();
public static void sleep(long millis): 在指定的毫秒数内让当前正在执行的线程休眠(暂停执行)。
try {
Thread.sleep(1000); // Sleep for 1 second
} catch (InterruptedException e) {
e.printStackTrace();
}
public static Thread currentThread(): 返回对当前正在执行的线程对象的引用。
Thread t = Thread.currentThread();
System.out.println("Current thread name: " + t.getName());
public final void setName(String name): 改变线程的名称。
t.setName("NewName");
public final String getName(): 返回该线程的名称。
System.out.println("Thread name: " + t.getName());
public final void setPriority(int newPriority): 更改线程的优先级。
t.setPriority(Thread.MAX_PRIORITY); // Set to maximum priority
public final int getPriority(): 返回线程的优先级。
System.out.println("Thread priority: " + t.getPriority());
public final void join(): 等待这个线程死亡。
try {
t.join(); // Wait for thread to die
} catch (InterruptedException e) {
e.printStackTrace();
}
public static void yield(): 暂停当前正在执行的线程对象,并执行其他线程。
Thread.yield(); // Yield execution
public final void interrupt(): 中断线程。
t.interrupt(); // Interrupt the thread
public static boolean interrupted(): 返回当前线程是否已经被中断。
if (Thread.interrupted()) {
// Thread is interrupted
}
public final boolean isAlive(): 测试这个线程是否还活