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

Java中的多线程函数有哪些,如何使用它们?

发布时间:2023-06-14 21:54:46

Java中有多种实现多线程的函数和类,其中常用的有Thread类、Runnable接口、Callable接口、Executor框架、Future和Semaphore等。

1. Thread类:

Java的Thread类是用来实现线程的主要类之一,使用方式如下:

public class MyThread extends Thread{
    @Override
    public void run(){
        //线程的逻辑
    }
}
//启动线程
MyThread thread = new MyThread();
thread.start();

2. Runnable接口:

另外一种实现线程的方式就是使用Runnable接口来定义线程,具体实现方式如下:

public class MyRunnable implements Runnable{
    @Override
    public void run(){
        //线程的逻辑
    }
}

//启动线程
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();

Runnable和Thread实现多线程的区别在于,Runnable实现更为灵活,因为可以继承其他类,并可拓展接口而不会影响线程的构造,而Thread类是final的,因此它不可继承。另外,使用Runnable的一个好处是,多个线程可以共享Runnable对象,从而实现更好的代码重用。

3. Callable接口:

Callable接口类似于Runnable接口但是比Runnable接口更为强大,Callable在使用时可以返回一个值,在需要多线程计算结果后调用get()方法获取值,Callable的一个典型用法就是定义“任务”,然后提供一种自定义的返回值类型。具体示例如下:

public class MyCallable implements Callable<String>{
    @Override
    public String call() throws Exception{
        //逻辑代码
        return "返回值";
    }
}
//启动线程
MyCallable myCallable = new MyCallable();
Future<String> future = executor.submit(myCallable);
String result = future.get();

4. Executor框架:

单独使用多线程的场景非常少,因为单独使用容易出现竞争条件、死锁等问题,而Java提供了Executor框架来管理线程池。Executor最常用的接口就是ExecutorService,它允许您通过submit()方法提交Callable或Runnable任务,并且返回Future对象,可以使用Future get()方法获取提交的任务的计算结果。具体使用示例:

ExecutorService executorService = Executors.newFixedThreadPool(10);

Callable<Integer> callable = () -> {
    //需要执行的逻辑
    return 1000;
};

Future<Integer> future = executorService.submit(callable);
Integer result = future.get();

//关闭线程池
executorService.shutdown();

5. Semaphore:

Semaphore是一个计数器,它用来控制同时访问某个共享资源的线程数量,也就是说,Semaphore可以看作是用来保护某个代码段的许可证,达到对公共资源的保护作用。Semaphore有两种方法,一个是acquire(),表示获取许可,另一个是release(),表示释放许可。示例:

public class SemaphoreTest {
    public static void main(String[] args) throws InterruptedException {
        Semaphore semaphore = new Semaphore(5);
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                try {
                    semaphore.acquire();//获取许可
                    System.out.println(Thread.currentThread().getName()+"获得了许可");
                    Thread.sleep(1000);//模拟任务执行
                    System.out.println(Thread.currentThread().getName()+"执行任务完成,释放许可");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    semaphore.release();//释放许可
                }
            }, "线程"+i).start();
        }

    }
}

以上是Java中常用的多线程实现方式和函数,可以根据实际需求选择合适的方法来进行多线程编程。