第四周作業-多線程編程

實驗內容

    大家可以選擇做 1,或選擇做2,全部做更鼓勵。

1:線程同步程序。P174-176 例8-4,把書籍代碼敲到Java文件中,運行結果,理解線程同步的原因與方法、創建新線程的方法等。

2:多線程的應用。我們從網絡下載數據,經常會使用多線程,如迅雷下載等,那麼怎麼實現的呢?請查看java下載網頁並讀取內容,以及本博主的其他相關內容、網絡上的內容,初步瞭解利用多線程下載網頁數據。


1、【例8-4】源程序名稱AccountTest1.java,實現線程同步的例子

class BankAccount{									//定義銀行賬戶類BankAccount
	private static int amount = 2000;				//定義餘額最初爲2000
	public void despoit(int m){						//定義存款方法
		amount = amount + m;
		System.out.println("小明存入["+m+" 元]");
	}
	public void withdraw(int m){					//定義取款方法
		amount = amount - m;
		System.out.println("張新取走["+m+"元]");
		if(amount<0)
			System.out.println("***餘額不足!***");
	}
	public int balance(){							//定義得到賬戶餘額的方法
		return amount;
	}			
}

class Customer extends Thread{
	String name;
	BankAccount bs;									//定義一個具體的賬戶對象
	public Customer(BankAccount b,String s){
		name = s;
		bs = b;
	}
	public synchronized static void cus(String name,BankAccount bs){
		if(name.equals("小明")){						//判斷用戶是不是小明
			try{
				for(int i=0;i<6;i++){
					Thread.currentThread().sleep((int)(Math.random()*300));
					bs.despoit(1000);
				}
			}
			catch(InterruptedException e){
			}
		}
		else{
			try{
				for(int i=0;i<6;i++){
					Thread.currentThread().sleep((int)(Math.random()*300));
					bs.withdraw(1000);
				}
			}
			catch(InterruptedException e){
			}
		}
	}
	public void run(){								//定義run方法
		cus(name,bs);
	}
}

public class AccountTest1 {
	public static void main(String[] args)throws InterruptedException {
		BankAccount bs = new BankAccount();
		Customer customer1 = new Customer(bs,"小明");
		Customer customer2 = new Customer(bs,"張新");
		Thread t1 = new Thread(customer1);
		Thread t2 = new Thread(customer2);
		t1.start();
		t2.start();
		Thread.currentThread().sleep(500);
	}
}

運行,結果


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章