谁帮我实现以下Java中的线程交替执行控制,要求按顺序输出1到100,代码如下。
发布网友
发布时间:2022-05-02 07:56
我来回答
共2个回答
热心网友
时间:2023-10-12 15:15
稍微修改下 未测试
package com.leejiliang.HomeworkDemo2;
/**
* 定义打印输出类,定义两个数据输出方法,分别用于输出偶数和奇数
*
* @author Administrator even偶数 uneven奇数
*/
class PrintNumber {
boolean isEven = true;
public void printEven() {
for (int i = 0; i <= 100; i = i + 2) {
if (i % 2 == 0) {
synchronized (this) {
while (!isEven) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("偶数:" + i);
isEven = false;
this.notify();
}
}
}
}
// 输出1到100之间的奇数
public void printUnEven() {
for (int i = 1; i <= 99; i = i + 1) {
if (i % 2 != 0) {
synchronized (this) {
while (isEven) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("奇数:" + i);
isEven = true;
this.notify();
}
}
}
}
}
/**
*
* @author Administrator 定义输出偶数的线程类
*/
class ThreadForEven implements Runnable {
private PrintNumber pn = null;
public ThreadForEven(PrintNumber pn) {
this.pn = pn;
}
@Override
public void run() {
pn.printEven();
}
}
/**
* 定义输出奇数的线程类
*
* @author Administrator
*
*/
class ThreadForUneven implements Runnable {
private PrintNumber pn = null;
public ThreadForUneven(PrintNumber pn) {
this.pn = pn;
}
@Override
public void run() {
pn.printUnEven();
}
}
// 主函数,执行两个线程
class ZeroToOneHundred {
public static void main(String[] args) {
PrintNumber pn = new PrintNumber();
ThreadForEven te = new ThreadForEven(pn);
ThreadForUneven tu = new ThreadForUneven(pn);
Thread threadeven = new Thread(te);
Thread threaneven = new Thread(tu);
threadeven.start();
threaneven.start();
}
}
热心网友
时间:2023-10-12 15:15
感觉是要两个线程。。。。。。。。但楼主这那么多线程,看着迷糊了追问就两个线程啊,可能我描述的不清楚!