gpt4 book ai didi

java - 奇偶序列java 2线程

转载 作者:行者123 更新时间:2023-12-01 07:55:32 26 4
gpt4 key购买 nike

我正在尝试编写一个具有两个 Java 线程的程序。一个打印奇数,另一个打印偶数。输出应该是按顺序的。我的代码无法正常工作。请更正并告诉我错误是什么。

public class App {

public static void main(String[] args) {
ThrdO to=new ThrdO();
Thread t1=new Thread(to);

ThredE te=new ThredE();
Thread t2=new Thread(te);
t1.start();


t2.start();
}

}

public class ThrdO implements Runnable{

PrintCl pcl =new PrintCl();

@Override
public void run() {
for(int i=0;i<10;i+=2)
pcl.Even(i);
}
}


public class ThredE implements Runnable {

PrintCl pcl =new PrintCl();

@Override
public void run() {
for(int i=1;i<10;i+=2)
try {
pcl.odd(i);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public class PrintCl {
public void Even(int n) {
synchronized (this) {
System.out.println(n);
this.notifyAll();
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

public void odd(int n) throws InterruptedException {

synchronized (this) {
System.out.println(n);
this.notifyAll();
this.wait();
}
}
}

获取输出

0 ,1

最佳答案

这是实现您想要的目标的一种更简洁的方法,代码中不会出现丑陋的 sleep ,更不用说它会比包含 sleep 的代码运行得更快,原因显而易见。

public class App {

public static void main(String[] args) {
PrintCl pcl = new PrintCl();

Thread t1 = new Thread(new ThrdEven(pcl));
Thread t2 = new Thread(new ThrdOdd(pcl));

t1.start();
t2.start();
}
}

public class ThrdEven implements Runnable {

private PrintCl pcl = null;

public ThrdEven(PrintCl pcl) {
this.pcl = pcl;
}

@Override
public void run() {
for (int i = 0; i < 10; i += 2) {
pcl.Even(i);
}
}
}

public class ThrdOdd implements Runnable {

private PrintCl pcl = null;

public ThrdOdd(PrintCl pcl) {
this.pcl = pcl;
}

@Override
public void run() {
for (int i = 1; i < 10; i += 2) {
pcl.odd(i);
}
}
}

public class PrintCl {

private final Object _lock = new Object();
private boolean isEvenAllowed = true;

public void Even(int n) {
synchronized (this._lock) {
while (!this.isEvenAllowed) {
try {
this._lock.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
throw new RuntimeException(e);
}
}
System.out.println(n);
this.isEvenAllowed = false;
this._lock.notifyAll();
}
}

public void odd(int n) {
synchronized (this._lock) {
while (this.isEvenAllowed) {
try {
this._lock.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
throw new RuntimeException(e);
}
}
System.out.println(n);
this.isEvenAllowed = true;
this._lock.notifyAll();
}
}
}

关于java - 奇偶序列java 2线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30658284/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com