交替顺序执行java代码
时间: 2023-07-09 12:31:40 浏览: 66
下面是一个示例代码,演示了两个任务按照一定的顺序交替执行:
```java
public class AlternatingSequenceExecution {
// 任务1
static class Task1 implements Runnable {
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("Executing task 1");
try {
Thread.sleep(1000); // 等待1秒钟
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
// 任务2
static class Task2 implements Runnable {
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("Executing task 2");
try {
Thread.sleep(1000); // 等待1秒钟
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
// 创建两个线程,分别执行任务1和任务2
Thread t1 = new Thread(new Task1());
Thread t2 = new Thread(new Task2());
// 启动两个线程,开始按照一定的顺序交替执行任务
t1.start();
try {
t1.join(); // 等待任务1执行完成
} catch (InterruptedException e) {
e.printStackTrace();
}
t2.start();
// 等待两个线程结束
try {
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
```
注意,这段代码演示了两个任务按照一定的顺序交替执行,先执行完任务1再执行任务2。在实际应用中,可以根据需要定义不同的执行顺序。