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); } }
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; } }
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."); } }
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

WebStorm Mac version
Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download
The most popular open source editor