//2、打印数字,读取通知
// (1)在main方法中启动两个线程;
// (2)在1个线程循环打印100以内的整数;
// (3)直到第2个线程从键盘读取了“Q”命令。
public class Test2 {
public static void main(String[] args) {
MyThread1 thread1 =new MyThread1();
MyThread2 thread2 =new MyThread2(thread1);
Thread t1 = new Thread(thread1);
Thread t2 = new Thread(thread2);
t2.start();
t1.start();
}
}
import java.util.Random;
public class MyThread1 implements Runnable{
public static boolean loop =true;
@Override
public void run() {
Random r =new Random();
while (loop){
try {
Thread.sleep(1000);
System.out.println(r.nextInt(100));
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
import java.util.Scanner;
public class MyThread2 implements Runnable{
private MyThread1 myThread1;
public MyThread2(MyThread1 myThread1) {
this.myThread1 = myThread1;
}
@Override
public void run() {
Scanner sc =new Scanner(System.in);
while (true) {
try {
Thread.sleep(1);
System.out.println("请输入您的指令:");
String input= sc.nextLine();
if(input.equals("q")){
myThread1.loop = false;
break;
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
————————————————
版权声明:本文为CSDN博主「柠稔875」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_74315371/article/details/128665089
双线程并发处理应用
最新推荐文章于 2024-09-16 10:50:12 发布