我已经看到了非常有益的许多类似的线程的问题,但我不明白,怎么他们的答案适用于这个问题。
我试图创建两个线程做两个不同的任务,相反,我创建了两个线程做同样的事情。
预期输出:
1 2 3 4 5 6 7 8 9 10
电流输出:
1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9
码:
package midtermpractice;
public class PrintNums {
public static class PrintRunnable implements Runnable {
int num;
public PrintRunnable(int x) {
this.num = x;
}
synchronized public void run() {
for (int i = this.num; i < 10; i++) {
System.out.print(i + " ");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.err.println(e);
}
}
}
}
public static void main(String[] args) {
Thread evenThread = new Thread(new PrintRunnable(1), "Even: ");
Thread oddThread = new Thread(new PrintRunnable(2), "Odd: ");
evenThread.start();
oddThread.start();
}
}
为了输出列表从0到9,则需要改变一些代码。首先,你需要了解的是:
奇数+ 2 =奇数
甚至+ 2 =甚至
我明白,你想一个线程打印奇数号码等,甚至打印的数字。随着中说,你需要改变几行代码。
for (int i = this.num; i <= 10; i+=2) {...}
和
Thread evenThread = new Thread(new PrintRunnable(0), "Even: ");
Thread oddThread = new Thread(new PrintRunnable(1), "Odd: ");