4.编写一个程序
public class MyThread extends Thread{
public void run(){
try{
for(int i=1;i<6;i++){
System.out.println(i);
sleep(2000);
}
}
catch(InterruptedException e){}
}
public static void main(String args[]){
System.out.println("当前的线程数:"+Thread.activeCount());
MyThread thread1=new MyThread();
thread1.start();
System.out.println("当前的线程数:"+Thread.activeCount());
MyThread thread2=new MyThread();
thread2.start();
System.out.println("当前的线程数:"+Thread.activeCount());
}
}
5张三和他的妻子各拥有一张银行卡和存折,可以对同一个银行账户进行存取款的操作。现银行账户中余款为500元,每人各取款五次,每次取款100元,在取款过程中存在网络延时。要求使用多线程模拟这个过程。
private String name;
public MuRun(String name) {
this.name = name;
}
@Override
public void run() {
synchronized(MuRun.class){
for(int i=0;i<5;i++){
if (test.money > 0) {
test.money = test.money - 100;
System.out.println(name + "取走了100元");
} else {
System.out.println(name + "没钱了");
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
Thread zf = new Thread(new MuRun("丈夫"));
Thread qz = new Thread(new MuRun("妻子"));
zf.start();
qz.start();
public class test {
public static int money = 500;
public static void main(String[] args) {
Thread zf = new Thread(new MuRun("丈夫"));
Thread qz = new Thread(new MuRun("妻子"));
zf.start();
qz.start();
}
}