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:
The following are code examples for some Java callback functions:
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!".
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".
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!