1.编写一个程序,创建两个线程对象,每个线程输出1~5的数。要求线程分别使用继承Thread类和现实Runnable接口两种方式创建。
package come.disizhang;
public class Test8 implements Runnable{
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.print(i+" ");
}
}
public static void main(String[] args) {
Thread thread = new Thread(new Test8());
thread.start();
}
}
package come.disizhang;
public class Test9 extends Thread{
public void run() {
super.run();
for (int i = 1; i <= 5; i++) {
System.out.print(i+" ");
}
}
public static void main(String[] args) {
Test9 test9 = new Test9();
test9.start();
}
}
2.张三和他的妻子各有一张银行卡和存折,可以对同一个银行账户进行存取款的操作。现银行账户余款为500元,每人各取款5次,每次取款100元,再取款过程中存在网络延迟。要求使用多线程模拟这个过程。
package come.disizhang;
public class Test5 extends Thread {
private String name; // 姓名
private int money; // 卡剩余额
private int time; // 网络延迟
private boolean flag = false; // 记录是否还有余额
/**
* 重写Thread的run方法 (non-Javadoc)
*/
public void run() {
while (!flag) {
sale();
}
}
/**
* 有参构造
*
* @param name
* @param money
* @param time
*/
public Test5(String name, int money, int time) {
super(name);
this.money = money;
this.time = time;
}
/*
*
* 线程同步(non-Javadoc)
*
* @see java.lang.Thread#run()
*/
public synchronized void sale() {
if (money <= 0) {// 卡里还有钱剩余就一直取
flag = true;
return;
}
money -= 100;
try {
Thread.sleep(this.time); // 网络延迟
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "准备取款");
System.out.println(Thread.currentThread().getName() + "完成取款");
System.out.println("余额不足以支付" + Thread.currentThread().getName() + "的取款,余额为零!");
}
}
package come.disizhang;
/**
* 测试类
* @author huang
*
*/
public class Test6 extends Thread{
public static void main(String[] args) {
Test5 test5 = new Test5("张三",500,500);
Test5 test51 = new Test5("张三的妻子",500,500);
test5.start();
test51.start();
}
}