//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);
}
}
}
}
打印数字,读取通知 (1)在main方法中启动两个线程 (2)在1个线程循环打印100以内的整数(3)直到第2个线程从键盘读取
最新推荐文章于 2024-11-12 21:14:07 发布