package test;
import java.util.Scanner;
/**
* @author 小小小白白白白
*/
public class DeadLock_ {
public static void main(String[] args) {
A a = new A();
new B(a).start();
a.start();
}
}
class A extends Thread{
private boolean loop=true;
@Override
public void run() {
while (loop) {
System.out.println((int)(Math.random() *100+1));
try {
Thread.sleep(1000);
} 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 key=scanner.next().toUpperCase().charAt(0);
if(key=='Q'){
a.setLoop(false);
break;
}
}
}
}
package test;
/**
* @author 小小小白白白白
*/
public class DeadLock_ {
public static void main(String[] args) {
Sell sell = new Sell();
new Thread(sell).start();
new Thread(sell).start();
}
}
class Sell implements Runnable{
private static int balance=10000;
@Override
public void run() {
while(true){
//同步代码块
synchronized(this){
if(balance<=0){
System.out.println("余额为空");
break;
}
balance=balance-1000;
System.out.println("用户:"+Thread.currentThread().getName()
+"消费1000元" +"余额:"+balance);
}
try {
Thread.sleep(700);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}