编写java程序

来源:百度知道 编辑:UC知道 时间:2024/07/03 08:24:35
用java编写程序,定义一个线程类,实现输出打印100以内能被3整除的数。创建2个线程对象同时执行,名字分别为“one”、“two”。

class PrintThread implements Runnable {
private String name;
private static Integer i;//100以内的数
private Object o;//锁对象

public PrintThread(String name, Integer i, Object o) {
this.name = name;
this.i = i;
this.o = o;
}

public void run() {
System.out.println(name + " start");
int temp = 0;//计数器
synchronized (o) {
while (i < 100) {
// System.out.println(name+" start");

if (i % 3 == 0) {
if (temp < 2) {//每个线程一次最多打印2个数
System.out.println(name + ": " + i);
temp++;
o.notifyAll();
} else {
temp = 0;
try {
o.wait();
} catch (Exception e) {
e.printStackTrace();
}
}
}
i++;
}
}
}
}

public class ThreadTest {
private static Integer i = 1;
public static void main(String[] args) {

Object o = new Object();
Runnable p1 = new PrintThread("ONE&qu