我想创建两个线程,第一个是偶数,第二个是奇数,我想要有同步列表来添加这个数字,最后打印数字,以便这是我的代码
@Override
public void run() {
synchronized (allNumber) {
for (int i = 1; i <=number ; i+=2) {
allNumber.add(i);
try {
allNumber.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
@Override
public void run() {
synchronized (allNumber){
for (int i = 0; i <= number; i+=2) {
allNumber.add(i);
allNumber.notify();
}
}
}
public class Main {
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) throws InterruptedException {
System.out.print("Enter Your Number: ");
int number = input.nextInt();
List<Integer> sharedList = new ArrayList<>();
Odd oddThread = new Odd(number, sharedList);
Even evenThread = new Even(number, sharedList);
Thread thread = new Thread(oddThread);
Thread thread1 = new Thread(evenThread);
thread.start();
thread1.start();
System.out.println("List: " + sharedList);
}
}
我的输出不按顺序且不完整
你想要数字按顺序排列,那么你必须确保线程相互等待。 我建议你这样写: 均匀
for (int i = 1; i <=number ; i+=2) {
if(i % 2 == 1){
synchronized (allNumber) {
if(i % 2 == 1){
allNumber.add(i);
}
}
}
}
奇怪
for (int i = 0; i <=number ; i+=2) {
if(i % 2 == 0){
synchronized (allNumber) {
if(i % 2 == 0){
allNumber.add(i);
}
}
}
}