欢迎访问宙启技术站
智能推送

多线程编程:常见java函数与示例

发布时间:2023-07-04 13:50:17

多线程编程是指在程序中并发执行多个任务的一种编程模型。在Java语言中,多线程编程可以通过使用Thread类或Runnable接口来创建线程,以实现多线程编程。

下面介绍一些常见的Java函数,以及对应的示例代码:

1. Thread类的常见方法:

- start():启动线程,开始执行线程中的任务。

- run():定义线程的执行逻辑,在start()方法被调用后会被自动执行。

- sleep(long millis):让当前线程休眠指定的时间。

- join():等待一个线程执行完毕后再继续执行当前线程。

示例代码:

Thread thread = new Thread(() -> {
    try {
        Thread.sleep(1000); // 线程休眠1秒
        System.out.println("Thread execution completed.");
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
});
thread.start();

2. Runnable接口的常见方法:

- run():定义线程的执行逻辑。

示例代码:

Runnable runnable = () -> {
    try {
        Thread.sleep(1000); // 线程休眠1秒
        System.out.println("Thread execution completed.");
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
};
Thread thread = new Thread(runnable);
thread.start();

3. synchronized关键字:用于保证线程的安全性,使得同一时间只有一个线程可以访问被synchronized修饰的代码块或方法。

示例代码:

class Counter {
    private int count = 0;

    public synchronized void increment() {
        count++;
    }

    public synchronized int getCount() {
        return count;
    }
}

Counter counter = new Counter();
Runnable runnable = () -> {
    for (int i = 0; i < 1000; i++) {
        counter.increment();
    }
};
Thread thread1 = new Thread(runnable);
Thread thread2 = new Thread(runnable);
thread1.start();
thread2.start();
thread1.join();
thread2.join();
System.out.println(counter.getCount()); // 2000

4. wait()、notify()和notifyAll():用于线程间的通信,wait()使线程等待,notify()唤醒等待的线程,notifyAll()唤醒所有等待的线程。

示例代码:

List<Integer> numbers = new ArrayList<>();
Runnable producer = () -> {
    synchronized (numbers) {
        for (int i = 1; i <= 10; i++) {
            numbers.add(i);
            System.out.println("Produced: " + i);
        }
        numbers.notifyAll();
    }
};
Runnable consumer = () -> {
    synchronized (numbers) {
        try {
            numbers.wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        for (Integer number : numbers) {
            System.out.println("Consumed: " + number);
        }
    }
};
Thread producerThread = new Thread(producer);
Thread consumerThread = new Thread(consumer);
producerThread.start();
consumerThread.start();

以上是一些常见的Java多线程编程函数和示例,可以通过使用这些函数来编写并发执行的多个任务。多线程编程能够提高程序的运行效率和资源利用率,但也需要注意线程安全问题,避免出现竞态条件等 bug。