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