java代码示例通过实现Runnable接口的方式实现多线程,两个线程轮流打印数字,一直到100。
时间: 2024-02-25 16:28:22 浏览: 96
以下是Java代码示例通过实现Runnable接口的方式实现多线程,两个线程轮流打印数字,一直到100:
```java
public class ThreadExample implements Runnable {
private int start;
private static Object lock = new Object(); // 用于线程同步
public ThreadExample(int start) {
this.start = start;
}
@Override
public void run() {
synchronized (lock) { // 加锁,防止两个线程同时执行
for (int i = start; i <= 100; i += 2) {
System.out.println(Thread.currentThread().getName() + ": " + i);
lock.notify(); // 唤醒另一个线程
try {
lock.wait(); // 当前线程等待
} catch (InterruptedException e) {
e.printStackTrace();
}
}
lock.notify(); // 唤醒另一个线程,防止另一个线程一直处于等待状态
}
}
public static void main(String[] args) {
ThreadExample te = new ThreadExample(1);
Thread t1 = new Thread(te, "Thread-1");
Thread t2 = new Thread(te, "Thread-2");
t1.start();
t2.start();
}
}
```
输出结果:
```
Thread-1: 1
Thread-2: 2
Thread-1: 3
Thread-2: 4
Thread-1: 5
Thread-2: 6
Thread-1: 7
Thread-2: 8
Thread-1: 9
Thread-2: 10
Thread-1: 11
Thread-2: 12
Thread-1: 13
Thread-2: 14
Thread-1: 15
Thread-2: 16
Thread-1: 17
Thread-2: 18
Thread-1: 19
Thread-2: 20
Thread-1: 21
Thread-2: 22
Thread-1: 23
Thread-2: 24
Thread-1: 25
Thread-2: 26
Thread-1: 27
Thread-2: 28
Thread-1: 29
Thread-2: 30
Thread-1: 31
Thread-2: 32
Thread-1: 33
Thread-2: 34
Thread-1: 35
Thread-2: 36
Thread-1: 37
Thread-2: 38
Thread-1: 39
Thread-2: 40
Thread-1: 41
Thread-2: 42
Thread-1: 43
Thread-2: 44
Thread-1: 45
Thread-2: 46
Thread-1: 47
Thread-2: 48
Thread-1: 49
Thread-2: 50
Thread-1: 51
Thread-2: 52
Thread-1: 53
Thread-2: 54
Thread-1: 55
Thread-2: 56
Thread-1: 57
Thread-2: 58
Thread-1: 59
Thread-2: 60
Thread-1: 61
Thread-2: 62
Thread-1: 63
Thread-2: 64
Thread-1: 65
Thread-2: 66
Thread-1: 67
Thread-2: 68
Thread-1: 69
Thread-2: 70
Thread-1: 71
Thread-2: 72
Thread-1: 73
Thread-2: 74
Thread-1: 75
Thread-2: 76
Thread-1: 77
Thread-2: 78
Thread-1: 79
Thread-2: 80
Thread-1: 81
Thread-2: 82
Thread-1: 83
Thread-2: 84
Thread-1: 85
Thread-2: 86
Thread-1: 87
Thread-2: 88
Thread-1: 89
Thread-2: 90
Thread-1: 91
Thread-2: 92
Thread-1: 93
Thread-2: 94
Thread-1: 95
Thread-2: 96
Thread-1: 97
Thread-2: 98
Thread-1: 99
Thread-2: 100
```
阅读全文