我已经开始在java中学习线程了。我已经编写了一个代码来按顺序打印奇数和偶数。但我得到的输出是两次。 以下是我的代码。
ThreadBasic1.java:
public class ThreadBasic1 {
public static void main(String[] args) {
Thread t1 = new Thread(new ThreadImplementation1());
Thread t2 = new Thread(new ThreadImplementation1());
t1.start();
t2.start();
}
}
ThreadImplementation1.java:
public class ThreadImplementation1 implements Runnable {
boolean isOdd= false;
@Override
public void run() {
System.out.println("thread started :: Thread name :: " + Thread.currentThread());
try {
for(int i = 1 ; i < 10 ; i++) {
if(i %2 ==0) {
printEven(i);
}
else {
printOdd(i);
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
synchronized void printEven(int number)throws InterruptedException {
while(!isOdd){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Even:"+number);
isOdd = false;
notifyAll();
}
synchronized void printOdd(int number) throws InterruptedException {
while (isOdd) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Odd :"+number);
isOdd = true;
notifyAll();
}
}
输出:
thread started :: Thread name :: Thread[Thread-1,5,main]
Odd :1
Even:2
Odd :3
Even:4
Odd :5
Even:6
Odd :7
Even:8
Odd :9
thread started :: Thread name :: Thread[Thread-0,5,main]
Odd :1
Even:2
Odd :3
Even:4
Odd :5
Even:6
Odd :7
Even:8
Odd :9
答案 0 :(得分:4)
你的问题很简单:你有两个完全相同的线程:打印从1到9的数字。
通常,此类练习要求您为每个线程设置略有不同的代码。一个线程仅打印奇数,其他线程打印偶数。然后两个线程都需要进入锁定步骤,以实现正确的1 2 3 4输出。或者你有“一个”线程实现,但你以某种方式启用配置该线程的行为。
因此,这里的答案是退后一步,重新思考整个方法。让两个线程执行相同是没有意义的。这只是意味着你重复某些行为。相反,想象一下如何对齐 两个不同的行为。
当然,我不会给你代码:练习的重点是你将这些想法变成代码。
答案 1 :(得分:0)
您可以在这里使用余数的概念。
如果number%2 == 1,则Odd将打印该数字并递增,否则它将进入等待状态。 如果number%2 == 0,则偶数将打印该数字并递增,否则它将进入等待状态。 让我们借助示例进行检查。
创建一个名为“ OddEvenRunnable”的类并实现Runnable接口。
class OddEvenRunnable implements Runnable {
public int PRINT_NUMBERS_UPTO = 10;
static int number = 1;
int remainder;
static Object lock = new Object();
public OddEvenRunnable(int remainder) {
this.remainder = remainder;
}
@Override
public void run() {
while (number < PRINT_NUMBERS_UPTO) {
synchronized (lock) {
while (number % 2 != remainder) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + " " + number);
number++;
lock.notifyAll();
}
}
}
}
public class PrintOddEvenMain {
public static void main(String[] args) {
OddEvenRunnable oddRunnable = new OddEvenRunnable(1);
OddEvenRunnable evenRunnable = new OddEvenRunnable(0);
Thread t1 = new Thread(oddRunnable, "Odd");
Thread t2 = new Thread(evenRunnable, "Even");
t1.start();
t2.start();
}
}
答案 2 :(得分:-1)
理想情况下,你应该只运行一个线程来执行切换作业b / w偶数和奇数。
package com.samples;
public class ThreadBasic1 {
public static void main(String[] args) {
Thread t1 = new Thread(new ThreadImplementation1());
Thread t2 = new Thread(new ThreadImplementation1());
t1.start();
//t2.start();
}
}