您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
在Java项目中,Runnable接口是一个非常有用的功能,它允许你创建多线程任务
public class MyRunnable implements Runnable {
private String taskName;
public MyRunnable(String taskName) {
this.taskName = taskName;
}
@Override
public void run() {
System.out.println("开始执行任务: " + taskName);
// 在这里编写你的任务代码
System.out.println("任务 " + taskName + " 已完成");
}
}
public class Main {
public static void main(String[] args) {
// 创建一个MyRunnable实例
MyRunnable myRunnable = new MyRunnable("示例任务");
// 创建一个Thread对象并将MyRunnable实例传递给它
Thread thread = new Thread(myRunnable);
// 启动线程
thread.start();
}
}
import java.util.concurrent.*;
public class MyCallable implements Callable<String> {
private String taskName;
public MyCallable(String taskName) {
this.taskName = taskName;
}
@Override
public String call() throws Exception {
System.out.println("开始执行任务: " + taskName);
// 在这里编写你的任务代码
String result = "任务 " + taskName + " 的结果";
System.out.println("任务 " + taskName + " 已完成");
return result;
}
}
public class Main {
public static void main(String[] args) {
// 创建一个MyCallable实例
MyCallable myCallable = new MyCallable("示例任务");
// 创建一个ExecutorService实例
ExecutorService executorService = Executors.newSingleThreadExecutor();
try {
// 提交Callable任务并获取Future对象
Future<String> future = executorService.submit(myCallable);
// 获取任务结果
String result = future.get();
System.out.println("任务结果: " + result);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
} finally {
// 关闭ExecutorService
executorService.shutdown();
}
}
}
这些示例展示了如何在Java项目中有效使用Runnable。你可以根据自己的需求修改这些示例,以适应你的项目。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。