package com.thread_;
import java.util.Scanner;
/*
在main方法中启动两个线程
第1个线程循环随机打印100以内的整数
直到第2个线程从键盘读取了“Q”命令。
*/
public class ThreadExercise {
public static void main(String[] args) {
A a = new A();
B b = new B(a);
a.start();
b.start();
}
}
class A extends Thread {
private boolean loop = true;
@Override
public void run() {
while (loop){
System.out.println((int)(Math.random()*100 + 1));
//休眠
try {
sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void setLoop(boolean loop) {
this.loop = loop;
}
}
class B extends Thread {
private A a;
private Scanner scanner= new Scanner(System.in);
public B(A a){
this.a = a;
}
@Override
public void run() {
while (true){
//接收键盘输入
System.out.println("输入Q并回车停止打印");
char str = scanner.next().toUpperCase().charAt(0);
if (str == 'Q'){
a.setLoop(false);
break;
}
}
}
}
package com.thread_;
/*
有2个用户分别从同一个卡上取钱(总额:10000)
每次都取1000,当余额不足时,就不能取款了
不能出现超取现象
*/
public class ThreadExercise2 {
public static void main(String[] args) {
User user = new User();
Thread thread1 = new Thread(user);
thread1.setName("user1");
Thread thread2 = new Thread(user);
thread2.setName("user2");
thread1.start();
thread2.start();
}
}
//涉及多个线程共享资源,故实现Runnable接口
class User implements Runnable {
private static int money = 10000;
@Override
public void run() {
while (true){
synchronized (this) {
money -= 1000;
System.out.println(Thread.currentThread().getName() + "取出1000元," + "余额" + money);
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (money <= 0){
System.out.println("余额不足!!!");
break;
}
}
}
}
标签:Thread,void,练习,线程,简单,new,public,loop
From: https://www.cnblogs.com/Q1u-ovo/p/17357240.html