高级特性 第4章

课后练习4:
package a4;

public class C4 extends Thread{
	public void run() {
		for (int i = 0; i < 5; i++) {
			System.out.print(i+1+" ");
		}
		System.out.println();
	}
}
package a4;

public class CC4 implements Runnable{
	public void run() {
		System.out.println();
		for (int i = 0; i < 5; i++) {
			System.out.print(i+1+" ");
		}
	}
}
package a4;

public class CCC4 {
	public static void main(String[] args) {
		Thread t1 = new Thread(new C4());
		Thread t2 = new Thread(new CC4());
		t1.start();
		t2.start();
	}
}

课后练习5:
package a4;

public class C5 implements Runnable{
	private int total = 500;
	public void run() {
		while(total > -400) {
			synchronized (this) {
				if(total >= 100) {
					System.out.println(Thread.currentThread().getName()+"准备取款");
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					System.out.println(Thread.currentThread().getName()+"完成取款");
					total -= 100;
				}else {
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					System.out.println("余额不足以支付"+Thread.currentThread().getName()+"的取款,余额为0");
					total -= 100;
				}
			}
		}
	}
	public static void main(String[] args) {
		C5 money = new C5();
		Thread man = new Thread(money,"张三");
		Thread woman = new Thread(money,"张三的妻子");
		man.start();
		woman.start();
	}
}

猜你喜欢

转载自blog.csdn.net/lsxdbd/article/details/80411208