1,编写一个程序,创建两个线程对象,每个线程输出1~5的数。
2,张三和他的妻子各拥有一张银行卡,可以对同一个账号进行存取款操作。现账户余额为500,每人各取5次,每次100元,在取款过程存在网络延时。要求使用多线程模拟过程。
package kehouzuoye; public class Number implements Runnable { @Override public void run() { for (int i = 0; i < 5; i++) { System.out.println(Thread.currentThread().getName()+" "+(i+1)); } } public static void main(String[] args) { Number nu = new Number(); Thread th = new Thread(nu,"线程A"); Thread th2 = new Thread(nu,"线程B"); th.start(); th2.start(); } }
2,张三和他的妻子各拥有一张银行卡,可以对同一个账号进行存取款操作。现账户余额为500,每人各取5次,每次100元,在取款过程存在网络延时。要求使用多线程模拟过程。
package kehouzuoye; public class Withdrawmoney implements Runnable { private int money = 500; private int num = 0; boolean flga = false; @Override public void run() { while (!flga) { money(); } } public synchronized void money() { if (money > 0) { try { Thread.sleep(500); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "准备取款\n" + Thread.currentThread().getName() + "完成取款!"); money -= 100; } else { flga = true; System.out.println("余额不足以支付" + Thread.currentThread().getName() + "款项" + "余额为:" + money); } } public static void main(String[] args) { Withdrawmoney wi = new Withdrawmoney(); Thread th = new Thread(wi,"张三"); Thread th2 = new Thread(wi,"张三妻子"); th.start(); th2.start(); } }