Home > Java > javaTutorial > Common scenarios: Understand how to use callback functions in Java

Common scenarios: Understand how to use callback functions in Java

WBOY
Release: 2024-02-01 09:21:06
Original
1305 people have browsed it

Common scenarios: Understand how to use callback functions in Java

Common usage scenarios of Java callback functions

The callback function is a common design pattern in functional programming, which allows a function to be passed to another function as a parameter. and be called under certain conditions. Callback functions are widely used in various scenarios in Java, including:

  • Event processing: Callback functions are usually used to handle various events, such as button clicks, mouse movements, keyboard Input etc. When an event occurs, the corresponding callback function will be called to perform the corresponding operation.
  • Asynchronous programming: Callback functions are also commonly used in asynchronous programming, that is, when an operation takes a long time to complete, the callback function can be passed as a parameter to the operation, and the operation Call the callback function when completed to avoid blocking the main thread.
  • Multi-threaded programming: In multi-threaded programming, callback functions can be used to coordinate communication and synchronization between different threads. When a thread needs to wait for another thread to complete a certain task, it can pass the callback function as a parameter to the thread and call the callback function after the task is completed, thereby achieving communication and synchronization between threads.

Code examples

The following are code examples for some Java callback functions:

  • Event handling:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ButtonExample {

    public static void main(String[] args) {
        // 创建一个按钮
        JButton button = new JButton("Click me!");

        // 添加一个点击事件监听器
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 当按钮被点击时,执行此代码
                System.out.println("Button clicked!");
            }
        });

        // 显示按钮
        JFrame frame = new JFrame();
        frame.add(button);
        frame.setSize(300, 300);
        frame.setVisible(true);
    }
}
Copy after login

In this example, when the button is clicked, the actionPerformed() method will be called, thus outputting "Button clicked!".

  • Asynchronous Programming:
import java.util.concurrent.CompletableFuture;

public class AsyncExample {

    public static void main(String[] args) {
        // 创建一个CompletableFuture对象
        CompletableFuture<Integer> future = new CompletableFuture<>();

        // 创建一个新线程来执行任务
        new Thread(() -> {
            // 执行任务
            int result = calculateSomething();

            // 将结果设置到CompletableFuture对象中
            future.complete(result);
        }).start();

        // 注册一个回调函数,当CompletableFuture对象完成时执行
        future.thenAccept(result -> {
            // 当任务完成时,执行此代码
            System.out.println("Result: " + result);
        });
    }

    private static int calculateSomething() {
        // 模拟一个耗时操作
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 返回结果
        return 42;
    }
}
Copy after login

In this example, the calculateSomething() method simulates a time-consuming operation, The thenAccept() method is a callback function. When the calculateSomething() method is completed, the thenAccept() method will be called, thus outputting "Result: 42".

  • Multi-threaded programming:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadExample {

    public static void main(String[] args) {
        // 创建一个线程池
        ExecutorService executorService = Executors.newFixedThreadPool(2);

        // 创建一个任务
        Runnable task = () -> {
            // 执行任务
            System.out.println("Task executed by thread: " + Thread.currentThread().getName());
        };

        // 将任务提交给线程池
        executorService.submit(task);

        // 注册一个回调函数,当所有任务都完成后执行
        executorService.shutdown();
        executorService.awaitTermination(1, TimeUnit.MINUTES);

        System.out.println("All tasks completed.");
    }
}
Copy after login

In this example, the submit() method submits the task to the thread pool , shutdown() method closes the thread pool, awaitTermination() method waits for all tasks to be completed, and finally outputs "All tasks completed.".

The above is the detailed content of Common scenarios: Understand how to use callback functions in Java. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template