📄 groupexam.java
字号:
import java.util.*;
public class groupExam{
public static void main(String[] args){
synClass obj;
Thread thread;
ThreadGroup group=new ThreadGroup("Thread Group");
for(int i=1;i<=3;i++){
obj=new synClass("用户 "+i);
thread=new Thread(group,obj);
thread.start();
}
System.out.println("Press \"Enter\" to stop...");
try{
System.in.read();
group.interrupt();
}
catch(Exception e){
}
}
}
class synClass
implements Runnable {
private static float balance = 100;
private String name;
private int count = 0;
public synClass(String name) {
this.name = name;
}
public void run() {
try {
Random r = new Random(); //随机调用存取款操作
while (true) {
int i = r.nextInt();
if (i % 3 == 0)
deposit(1000);
else if (i % 3 == 1)
withdraw(500);
else
getBalance();
count++;
Thread.sleep(100);
}
}
catch (InterruptedException e) {
}
}
public synchronized void getBalance() {
System.out.println("帐户余额:" + balance);
}
public synchronized void deposit(float n) {
System.out.println(name + " 存入 " + n);
balance += n;
}
public synchronized void withdraw(float n) {
if (balance >= n) {
System.out.println(name + " 支取 " + n);
balance -= n;
}
else
System.out.println(name + " 支取 " + n + " 失败,余额不足");
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -