Runnable

  1 import java.lang.Runnable;
  2 import java.lang.Thread;
  3 import java.util.concurrent.Executors;
  4 import java.util.concurrent.ExecutorService;
  5 import java.util.concurrent.Future;
  6 import java.util.concurrent.ExecutionException;
  7
  8 class runclass implements Runnable {
  9     public static long id = 0;
 10     
 11     public void run(){
 12         ++id;
 13         System.out.println(id);
 14     }
 15 }
 16
 17 class test {
 18     public static void main(String[] args) throws InterruptedException, ExecutionException {
 19         ExecutorService exec = Executors.newCachedThreadPool();
 20         Future result1 = exec.submit(new runclass());
 21         Future result2 = exec.submit(new runclass());
 22         while (!result1.isDone() || !result2.isDone()){
 23             Thread.sleep(1000);
 24             break;
 25         }
 26         exec.shutdown();
 27     }
 28 }
 29

### Java 中 `Runnable` 接口的使用与实现 #### 定义与功能 `Runnable` 是 Java 提供的一个核心接口,用于定义线程的任务逻辑。通过实现该接口并重写其唯一的抽象方法 `run()`,可以指定线程执行的具体操作[^1]。 以下是关于如何创建和使用 `Runnable` 的具体说明: #### 创建方式 可以通过以下两种主要方式来利用 `Runnable` 接口: 1. **直接实现 `Runnable` 接口** 实现此接口后,在类中提供具体的任务逻辑,并将其传递给 `Thread` 类实例化对象。 ```java class MyRunnable implements Runnable { @Override public void run() { System.out.println("Task is being executed by " + Thread.currentThread().getName()); } } public class Main { public static void main(String[] args) { Thread thread = new Thread(new MyRunnable()); thread.start(); } } ``` 2. **结合 `FutureTask` 使用** 如果需要支持异步计算的结果返回或者取消机制,则可以选择将 `Runnable` 封装到 `FutureTask` 中。这种方式允许更复杂的控制流管理[^2]。 ```java import java.util.concurrent.Callable; import java.util.concurrent.FutureTask; class MyCallable implements Callable<String> { @Override public String call() throws Exception { return "Result from callable"; } } public class Main { public static void main(String[] args) throws Exception { FutureTask<String> futureTask = new FutureTask<>(new MyCallable()); Thread thread = new Thread(futureTask); thread.start(); System.out.println("Result: " + futureTask.get()); // Blocks until result available. } } ``` #### 注意事项 当设计多线程程序时需要注意资源共享问题以及可能引发的竞争条件等问题。此外,虽然可以直接继承 `Thread` 来达到相同目的,但通常推荐优先考虑实现 `Runnable` 或者其他更高层次的并发工具(如 ExecutorService),因为这样能够更好地遵循面向对象的设计原则——即避免多重继承带来的复杂性和局限性。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值