java中如何开启多个线程,根据不同的条件执行不同的逻辑
时间: 2023-10-31 17:05:18 浏览: 39
在 Java 中,可以通过实现 Runnable 接口或继承 Thread 类来开启多个线程。以下是实现 Runnable 接口的示例代码:
```
public class MyRunnable implements Runnable {
private String condition;
public MyRunnable(String condition) {
this.condition = condition;
}
public void run() {
if (condition.equals("condition1")) {
// 执行逻辑1
} else if (condition.equals("condition2")) {
// 执行逻辑2
} else {
// 执行逻辑3
}
}
}
public class Main {
public static void main(String[] args) {
Thread thread1 = new Thread(new MyRunnable("condition1"));
Thread thread2 = new Thread(new MyRunnable("condition2"));
Thread thread3 = new Thread(new MyRunnable("condition3"));
thread1.start();
thread2.start();
thread3.start();
}
}
```
在上面的代码中,我们实现了一个 MyRunnable 类,它实现了 Runnable 接口。MyRunnable 类有一个构造函数,可以传入一个条件,根据不同的条件来执行不同的逻辑。在 Main 类中,我们创建了三个线程,并分别传入不同的条件,然后启动这三个线程。
除了实现 Runnable 接口之外,还可以通过继承 Thread 类来开启多个线程,具体实现方法和上面类似。