package 交替输出数据;
class Number implements Runnable {
int minNum = 6; // 定义从那个数开始输出(不包括该数)
int xianChengNum = 3; // 参与执行的线程个数
int eachThreadPrintNum = 10; //定义每个线程输出多少个数
int maxNum = 75; //输出到那个数结束(包含结束数字)
@Override
public synchronized void run() {
// TODO Auto-generated method stub
while (minNum < maxNum) {
String tName = Thread.currentThread().getName();
// minNum / eachThreadPrintNum 代表从min到max需要多少次线程执行!
int temp = minNum / eachThreadPrintNum % xianChengNum;
if (tName.equals(String.valueOf(temp))) {
System.out.print(tName + " : ");
for (int i = 0; i < eachThreadPrintNum; i++) {
minNum++;
if(minNum>maxNum){
break;
}
System.out.print(minNum + " ");
}
System.out.println(" ");
notifyAll();
} else {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
public class Print {
public static void main(String[] args) {
Number number = new Number();
Thread t1 = new Thread(number, "0");
Thread t2 = new Thread(number, "1");
Thread t3 = new Thread(number, "2");
t2.start();
t1.start();
t3.start();
}
}
多线程交替输出数据
最新推荐文章于 2023-03-05 21:08:27 发布