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

Java多线程函数库的使用案例

发布时间:2023-05-24 08:04:15

Java是一种面向对象的程序设计语言,它支持多线程编程。使用Java多线程函数库,可以在不同的线程中执行不同的任务,大大提高程序的执行效率和性能。

下面,介绍几个Java多线程函数库的使用案例。

1. Executor框架

Executor框架是Java多线程函数库中的一种较为常用的函数库,它提供了简单的线程管理和执行模型。下面是一个使用Executor框架的例子。

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ExecutorExample {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 10; i++) {
            Runnable worker = new WorkerThread("" + i);
            executor.execute(worker);
        }
        executor.shutdown();
        while (!executor.isTerminated()) {
        }
        System.out.println("Finished all threads");
    }
}

class WorkerThread implements Runnable {
    private String message;

    public WorkerThread(String s){
        this.message=s;
    }

    public void run() {
        System.out.println(Thread.currentThread().getName()+" (Start) message = "+message);
        processMessage();//call processmessage method that sleeps the thread for 2 seconds
        System.out.println(Thread.currentThread().getName()+" (End)");
    }

    private void processMessage() {
        try {  Thread.sleep(2000);  } catch (InterruptedException e) { e.printStackTrace(); }
    }
}

这个例子中,我们定义了一个名为“WorkerThread”的类,它实现了Runnable接口,并重写了run()方法和processMessage()方法。在main()方法中,我们使用Executor框架创建了一个线程池,并将任务提交给线程池执行。最后,等待所有线程执行完成后,打印“Finished all threads”。

2. Callable接口

Callable接口与Runnable接口类似,但是它可以返回结果。使用Callable接口可以在线程执行完成后获取执行结果。下面是一个使用Callable接口的例子。

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class CallableExample {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(5);
        Future<Integer> future = executor.submit(new Callable<Integer>() {
            public Integer call() throws Exception {
                int sum = 0;
                for (int i = 1; i <= 100; i++) {
                    sum += i;
                }
                return sum;
            }
        });
        executor.shutdown();
        while (!future.isDone()) {
        }
        try {
            System.out.println("Sum of 1 to 100 is : " + future.get());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

这个例子中,我们定义了一个Callable接口对象,并提交给线程池执行。Future对象代表了线程执行的结果,我们可以使用它的get()方法获取执行结果。

3. Semaphore类

Semaphore类是Java多线程函数库中的一个类,它用来控制可访问某些资源的线程数目。下面是一个使用Semaphore类的例子。

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class SemaphoreExample {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newCachedThreadPool();
        Semaphore semaphore = new Semaphore(3);
        for (int i = 0; i < 10; i++) {
            Runnable worker = new WorkerThread(i, semaphore);
            executor.execute(worker);
        }
        executor.shutdown();
        while (!executor.isTerminated()) {
        }
        System.out.println("Finished all threads");
    }
}

class WorkerThread implements Runnable {
    private int workerNumber;
    private Semaphore semaphore;

    public WorkerThread(int workerNumber, Semaphore semaphore) {
        this.workerNumber = workerNumber;
        this.semaphore = semaphore;
    }

    public void run() {
        try {
            semaphore.acquire();
            System.out.println("Worker " + workerNumber + " acquires the semaphore.");
            Thread.sleep((int) (Math.random() * 1000));
            System.out.println("Worker " + workerNumber + " releases the semaphore.");
            semaphore.release();
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }
    }
}

这个例子中,我们定义了一个Semaphore对象,它控制着同时执行的最大线程数。线程获取该Semaphore对象后,执行一些任务后释放该Semaphore对象。这样可以保证同时只有最多3个线程在执行。

以上是几个Java多线程函数库的使用案例,希望读者可以通过这些例子加深对Java多线程编程的理解。