高级特性第四章课后作业

4.要求使用线程分别使用继承Thread类和实现Runnable接口两种方式输出1-5的数
package thread;

public class NumTest extends Thread implements Runnable {

	public void run() {
		for (int i = 0; i < 5; i++) {
			System.out.print(i+1+" ");
		}
	}
	public static void main(String[] args) {
		NumTest num = new NumTest();
		Thread thread= new Thread(new NumTest());
		num.start();
		thread.run();
	}

}
5.模拟取款
package thread;

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

	public void run() {
		for (int i = 0; i < 5; i++) {
			if (i==3) {
				Thread.yield();
			}
			take();
		}														
		}
	public synchronized void take() {
	
		if (money > 0) {
			System.out.println(Thread.currentThread().getName() + "准备取款");
			System.out.println(Thread.currentThread().getName() + "取款成功");
			try {
				Thread.sleep(500);

			} catch (InterruptedException e) {

				e.printStackTrace();
			}
			money -= 100;
		}else {
			System.out.println("余额不足以支付" + Thread.currentThread().getName() + "的取款");
		}
	}

}
package thread;

public class TestTakemoney {
	public static void main(String[] args) {
		TakeMoney money= new TakeMoney();
		Thread man = new Thread( money,"张三");
		Thread woman = new Thread(money,"张三老婆");
		man.start();
		woman.start();

	}

}


猜你喜欢

转载自blog.csdn.net/tb19930719/article/details/80421639