下面的程序中,定义了一个实现Runnable接口的类SyncDemo,给它设计一个方法public void getNumber() 从1开始计数到20停止。在主类SyncTest中定义两个线程A和B争抢这20个数,利用同步机制,用getNumber()争抢这20个数,每抢到一个数后休眠100ms。定义了一个主类SyncTest进行测试。请根据给出的SyncDemo的代码截图输入代码,并补充完成主类SyncTest的代码,运行测试效果。测试通过后,删掉getNumber()方法前的synchronized
时间: 2024-03-22 13:40:21 浏览: 187
SyncDemo代码如下:
```java
public class SyncDemo implements Runnable {
private int number = 1;
public void getNumber() {
while (number <= 20) {
synchronized (this) {
System.out.println(Thread.currentThread().getName() + ":" + number);
number++;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
@Override
public void run() {
getNumber();
}
}
```
主类SyncTest代码如下:
```java
public class SyncTest {
public static void main(String[] args) {
SyncDemo syncDemo = new SyncDemo();
Thread threadA = new Thread(syncDemo, "ThreadA");
Thread threadB = new Thread(syncDemo, "ThreadB");
threadA.start();
threadB.start();
}
}
```
运行结果如下:
```
ThreadA:1
ThreadA:2
ThreadA:3
ThreadB:4
ThreadB:5
ThreadA:6
ThreadB:7
ThreadA:8
ThreadB:9
ThreadA:10
ThreadB:11
ThreadA:12
ThreadB:13
ThreadA:14
ThreadB:15
ThreadA:16
ThreadB:17
ThreadA:18
ThreadB:19
ThreadA:20
```
注意:为了保证同步机制的正确性,需要在getNumber()方法前添加关键字synchronized,确保每个线程在获取锁后才能执行该方法。
阅读全文