使用JAVA代码完成以下题目 1.定义一个品牌计算机的枚举类,里面只有固定的几个计算机品牌,例如:Lenovo、HP、Dell、Apple、Acer 2.定义四个行线程操作,两个线程执行减操作,两个线程执行加操作
时间: 2023-12-03 16:43:33 浏览: 66
编写计算器类,实现加法、减法操作,使用JAVA反射机制动态调用计算器对象的加法,减法函数
5星 · 资源好评率100%
1. 定义品牌计算机的枚举类
```java
public enum ComputerBrand {
LENOVO,
HP,
DELL,
APPLE,
ACER
}
```
2. 定义四个线程类,两个线程执行减操作,两个线程执行加操作
```java
class AddThread implements Runnable {
private int value = 0;
private Object lock = new Object();
public void run() {
while (true) {
synchronized (lock) {
value++;
System.out.println(Thread.currentThread().getName() + " add value: " + value);
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class SubThread implements Runnable {
private int value = 0;
private Object lock = new Object();
public void run() {
while (true) {
synchronized (lock) {
value--;
System.out.println(Thread.currentThread().getName() + " sub value: " + value);
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
```
3. 创建主线程,启动四个子线程
```java
public class Main {
public static void main(String[] args) {
Thread addThread1 = new Thread(new AddThread(), "AddThread1");
Thread addThread2 = new Thread(new AddThread(), "AddThread2");
Thread subThread1 = new Thread(new SubThread(), "SubThread1");
Thread subThread2 = new Thread(new SubThread(), "SubThread2");
addThread1.start();
addThread2.start();
subThread1.start();
subThread2.start();
}
}
```
阅读全文