Java 线程的基本操作(java线程的三种方式)

Java 线程的基本操作包括创建、启动、暂停、中断、等待和终止等。以下是这些操作的详细说明和示例代码:


1.创建线程

Java 中创建线程有两种方式:

  • o 继承 Thread
  • o 实现 Runnable 接口(推荐,更灵活)。

示例:继承Thread类

class MyThread extends Thread {
    @Override
    public void run() {
        System.out.println("线程正在运行...");
    }
}

public class Main {
    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start(); // 启动线程
    }
}

示例:实现Runnable接口

class MyRunnable implements Runnable {
    @Override
    public void run() {
        System.out.println("线程正在运行...");
    }
}

public class Main {
    public static void main(String[] args) {
        Thread thread = new Thread(new MyRunnable());
        thread.start(); // 启动线程
    }
}

2.启动线程

  • o 调用 start() 方法启动线程,线程进入 RUNNABLE 状态。
  • o 注意:直接调用 run() 方法不会启动新线程,而是在当前线程中执行。

3.暂停线程

  • o 使用 Thread.sleep(long millis) 方法让线程暂停指定时间(进入 TIMED_WAITING 状态)。
  • o 注意sleep() 不会释放锁。

示例:

public class Main {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            try {
                System.out.println("线程开始休眠...");
                Thread.sleep(2000); // 休眠 2 秒
                System.out.println("线程恢复运行...");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        thread.start();
    }
}

4.中断线程

  • o 使用 interrupt() 方法中断线程。
  • o 线程可以通过 isInterrupted() 检查中断状态,或通过 InterruptedException 捕获中断信号。

示例:

public class Main {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            while (!Thread.currentThread().isInterrupted()) {
                System.out.println("线程正在运行...");
                try {
                    Thread.sleep(1000); // 休眠 1 秒
                } catch (InterruptedException e) {
                    System.out.println("线程被中断!");
                    Thread.currentThread().interrupt(); // 重新设置中断状态
                }
            }
        });
        thread.start();

        try {
            Thread.sleep(3000); // 主线程休眠 3 秒
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        thread.interrupt(); // 中断线程
    }
}

5.等待线程结束

  • o 使用 join() 方法让当前线程等待目标线程执行完毕。

示例:

public class Main {
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(() -> {
            try {
                Thread.sleep(2000); // 模拟耗时操作
                System.out.println("子线程执行完毕!");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        thread.start();

        System.out.println("主线程等待子线程结束...");
        thread.join(); // 主线程等待子线程结束
        System.out.println("主线程继续执行...");
    }
}

6.设置线程优先级

  • o 使用 setPriority(int priority) 方法设置线程优先级(1~10,默认 5)。
  • o 注意:优先级只是提示,具体调度由操作系统决定。

示例:

public class Main {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            System.out.println("线程优先级: " + Thread.currentThread().getPriority());
        });
        thread.setPriority(Thread.MAX_PRIORITY); // 设置为最高优先级
        thread.start();
    }
}

7.守护线程

  • o 使用 setDaemon(true) 将线程设置为守护线程。
  • o 当所有非守护线程结束时,守护线程会自动终止。

示例:

public class Main {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            while (true) {
                System.out.println("守护线程正在运行...");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        thread.setDaemon(true); // 设置为守护线程
        thread.start();

        System.out.println("主线程结束,守护线程也会终止。");
    }
}

8.终止线程

  • o Java 没有直接终止线程的方法,推荐通过标志位或中断机制优雅地终止线程。

示例:使用标志位终止线程

public class Main {
    public static void main(String[] args) throws InterruptedException {
        class StoppableThread extends Thread {
            private volatile boolean stopped = false; // 标志位

            @Override
            public void run() {
                while (!stopped) {
                    System.out.println("线程正在运行...");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("线程已终止!");
            }

            public void stopThread() {
                stopped = true; // 修改标志位
            }
        }

        StoppableThread thread = new StoppableThread();
        thread.start();

        Thread.sleep(3000); // 主线程休眠 3 秒
        thread.stopThread(); // 终止线程
    }
}

9.线程同步

  • o 使用 synchronized 关键字或 Lock 实现线程同步,避免资源竞争。

示例:使用synchronized

public class Main {
    private static int counter = 0;

    public static void main(String[] args) throws InterruptedException {
        Runnable task = () -> {
            for (int i = 0; i < 1000; i++) {
                synchronized (Main.class) { // 同步代码块
                    counter++;
                }
            }
        };

        Thread thread1 = new Thread(task);
        Thread thread2 = new Thread(task);
        thread1.start();
        thread2.start();

        thread1.join();
        thread2.join();
        System.out.println("Counter: " + counter); // 输出 2000
    }
}

总结

  • o Java 线程的基本操作包括创建、启动、暂停、中断、等待、终止和同步等。
  • o 推荐使用 Runnable 接口创建线程,避免直接继承 Thread 类。
  • o 使用 interrupt() 和标志位优雅地终止线程,避免使用已废弃的 stop() 方法。
  • o 多线程编程时注意线程安全问题,合理使用同步机制。

希望这些示例能帮助你掌握 Java 线程的基本操作!

#java##java 编程##线程##android开发者#

原文链接:,转发请注明来源!