Hello,今天写了一个多线程的打印数字的程序,在多线程问题里面也很具有代表性,感兴趣的同学们一起来看看吧。
程序需求:
/**
* 启动3个线程打印递增的数字
* 线程1先打印1,2,3,4,5
* 线程2打印6,7,8,9,10
* 线程3打印11,12,13,14,15
* 接着再由线程1打印16,17,18,19,20….以此类推, 直到打印到75
*/
实现思路:1、因为打印数字要连续,所以我们要在打印类里面定义一个数字属性,帮助我们打印结果,同时打印类里面还要有一个属性来帮助我们判断需要调用哪个线程的标记。
2、创建一个测试类,里面生成三个线程,通过3个线程循环5次,每个线程每次输出5个数字来实现75个数字的打印。
思路说完了,具体源代码如下:
打印类代码:
/**
* @author 小河子~
* @VX xiaohe66i
* @date 2021年06月11日 22:20
*/
public class PrintNum {
private int num=1;
private int flag=1;
public synchronized void print1 (){
while (flag!=1){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print(Thread.currentThread().getName()+":");
for (int i = 1; i <= 5; i++) {
System.out.print(num+" ");
num++;
}
//换行
System.out.println();
flag++;
//唤醒其它线程
this.notifyAll();
}
public synchronized void print2 (){
while (flag!=2){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print(Thread.currentThread().getName()+":");
for (int i = 1; i <= 5; i++) {
System.out.print(num+" ");
num++;
}
//换行
System.out.println();
flag++;
this.notifyAll();
}
public synchronized void print3 (){
while (flag!=3){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print(Thread.currentThread().getName()+":");
for (int i = 1; i <= 5; i++) {
System.out.print(num+" ");
num++;
}
//换行
System.out.println();
flag=1;
this.notifyAll();
}
}
程序测试类:
/**
* @author 小河子~
* @VX xiaohe66i
* @date 2021年06月11日 22:08
*/
public class Question3Demo {
public static void main(String[] args) {
PrintNum printNum = new PrintNum();
for (int i = 0; i <5 ; i++) {
Runnable A=new Runnable() {
@Override
public void run() {
printNum.print1();
}
};
Runnable B=new Runnable() {
@Override
public void run() {
printNum.print2();
}
};
Runnable C=new Runnable() {
@Override
public void run() {
printNum.print3();
}
};
Thread t1=new Thread(A,"线程1");
Thread t2=new Thread(B,"线程2");
Thread t3=new Thread(C,"线程3");
t1.start();
t2.start();
t3.start();
}
}
}
程序运行截图:
好了,今天这个很简单的一个小程序就到这里结束了,每天进步一点点,欢迎感兴趣的同学一起交流学习~