第4章 课后作业

第4题 使用继承Thread类和实现runnable接口两种方式创建两个线程对象,每个线程对象输出1~5的数

/**
 * 实现runnable接口
 */
public class MyRunnable implements Runnable {
public void run() {
for (int i = 0; i < 5; i++) {
System.out.print((i+1)+" ");
}
}

}

/**
 * 继承Thread类
 */
public class MyThread extends Thread {
public void run() {
for (int i = 0; i < 5; i++) {
System.out.print((i+1)+" ");
}
}

}

/**
 * 测试类
 */
public class Test {
public static void main(String[] args) {
MyThread myThread = new MyThread();
System.out.println("继承Thread类创建:");
myThread.start();
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
System.out.println("\n实现runnable接口创建:");
thread.start();
}

}

第5题  模拟银行取款,两人同时取款

public class Withdrawals implements Runnable {
private int money = 500;

public void run() {
  for (int i = 0; i < 5; i++) {
withdraw();
}
}

public synchronized void withdraw() {
if (money <= 0) {
System.out.println("余额不足以支付"+Thread.currentThread().getName()+"的取款,余额为:" + money);
return;
}

System.out.println(Thread.currentThread().getName() + "准备取钱\n" + Thread.currentThread().getName() + "完成取钱");
money-=100;
System.out.println(Thread.currentThread().getName()+"取款成功,余额"+money);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Withdrawals w = new Withdrawals();
Thread t = new Thread(w,"张三");
Thread t1 = new Thread(w,"张三的老婆");
t.start();
t1.start();
}
}

猜你喜欢

转载自blog.csdn.net/weixin_41880408/article/details/80401524