温馨提示×

java中thread类的方法怎么使用

小亿
84
2024-01-10 20:09:41
栏目: 编程语言

Java中Thread类的方法可以通过创建Thread对象来使用。以下是一些常用的Thread类方法:

  1. start():启动线程,使其进入就绪状态,并执行run()方法。
  2. run():定义线程的执行逻辑,可以重写该方法以实现多线程的功能。
  3. sleep(long milliseconds):使当前线程休眠指定的毫秒数。
  4. join():等待该线程终止。
  5. interrupt():中断线程。
  6. isInterrupted():判断线程是否被中断。
  7. getName():获取线程的名称。
  8. setName(String name):设置线程的名称。
  9. isAlive():判断线程是否存活。
  10. yield():使当前线程让出CPU执行权,让其他线程有更多的机会执行。

以下是一个示例代码,展示了如何使用Thread类的方法:

public class MyThread extends Thread {
    public void run() {
        // 线程的执行逻辑
        for (int i = 0; i < 5; i++) {
            System.out.println("Thread " + getName() + ": " + i);
            try {
                sleep(1000); // 线程休眠1秒
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        MyThread thread1 = new MyThread();
        thread1.setName("Thread 1");
        
        MyThread thread2 = new MyThread();
        thread2.setName("Thread 2");

        thread1.start(); // 启动线程1
        thread2.start(); // 启动线程2

        try {
            thread1.join(); // 等待线程1终止
            thread2.join(); // 等待线程2终止
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        
        System.out.println("Main thread finished");
    }
}

以上代码中,首先创建了两个MyThread对象,并设置它们的名称。然后通过调用start()方法启动线程,并执行run()方法中的逻辑。在main方法中,使用join()方法等待两个线程终止,最后打印出"Main thread finished"。

0