Java實(shí)戰(zhàn)教程,實(shí)現(xiàn)網(wǎng)絡(luò)之并發(fā)編程

Java實(shí)戰(zhàn)教程,實(shí)現(xiàn)網(wǎng)絡(luò)之并發(fā)編程

長(zhǎng)沙一度軟件培訓(xùn)      2022-04-02 05:00:01     10

Java實(shí)戰(zhàn)教程,實(shí)現(xiàn)網(wǎng)絡(luò)之并發(fā)編程,1.并發(fā)與并行個(gè)人理解并發(fā)就是在時(shí)間上運(yùn)行程序(即不同任務(wù)在不同時(shí)間片上運(yùn)行),并行就是在空間上運(yùn)行程序(即不同任務(wù)在不同

課程價(jià)格 請(qǐng)咨詢

上課時(shí)段: 授課校區(qū):

詳細(xì)介紹

1.并發(fā)與并行

個(gè)人理解并發(fā)就是在時(shí)間上運(yùn)行程序(即不同任務(wù)在不同時(shí)間片上運(yùn)行),并行就是在空間上運(yùn)行程序(即不同任務(wù)在不同處理器或計(jì)算機(jī)上運(yùn)行)。

2.Java中的Thread類

(1)Thread類通過實(shí)現(xiàn)Runnable接口

(2)線程池(ThreadPool)用來管理線程的數(shù)量

我們先用一個(gè)例子實(shí)現(xiàn):

  • 創(chuàng)建并啟動(dòng)100個(gè)線程,每個(gè)線程都往同一個(gè)賬戶添加一元。
  • 定義一個(gè)名為Account類模擬賬戶,一個(gè)名為AddAYuanTask的類用來向賬戶里添加一元。

程序如下

第一版Accountimport?java.util.concurrent.*;public?class?AccountWithoutSync?{????private?static?Account?account?=?new?Account();????public?static?void?main(String[]?args)????{????????ExecutorService?executor?=?Executors.newCachedThreadPool();????????for(int?i?=?0;?i?<?100;?i++)????????{????????????executor.execute(new?AddoneYuanTask());????????}????????executor.shutdown();?????????while(!executor.isTerminated())????????{?????????????}?????????System.out.println("What?is?balance??"?+?account.getBalance());????}????????//Inner?class????private?static?class?AddOneYuanTask?implements?Runnable????{????????public?void?run()????????{????????????account.deposit(1);????????}????}????????private?static?class?Account????{????????private?int?balance?=?0;????????????????public?int?getBalance()????????{????????????return?balance;????????}????????????????public?void?deposit(int?amount)????????{????????????int?newBalance?=?balance?+?amount;????????????????????????????????????//人為地制造延時(shí)??????????????try????????????{????????????????Thread.sleep(5);????????????}????????????catch(InterruptedException?ex)????????????{????????????}????????????????????????balance?=?newBalance;????????}????}}

我們運(yùn)行一下發(fā)現(xiàn)balance為4或5,這是個(gè)錯(cuò)誤的結(jié)果,如果一個(gè)類的對(duì)象在多線程程序中導(dǎo)致競(jìng)爭(zhēng)狀態(tài),則稱這個(gè)類為線程不安全的。所以這個(gè)任務(wù)是線程不安全的。

3.用同步完善程序

用互斥鎖來實(shí)現(xiàn)同步,即在一任務(wù)開始執(zhí)行時(shí)加鎖,執(zhí)行完畢后釋放鎖。在釋放鎖之前其它任務(wù)無法執(zhí)行。同步完全可以避免競(jìng)爭(zhēng)狀態(tài)的產(chǎn)生,但有的時(shí)候還需要線程之間的相互合作。

然后增加一個(gè)向賬戶提款(Withdraw)的任務(wù),當(dāng)余額小于取款數(shù)時(shí),等待新存入的存款。

Account類添加

privatestaticLocklock=newReentrantLock();//創(chuàng)建一個(gè)鎖

privatestaticConditionnewDeposit=lock.newCondition();//實(shí)現(xiàn)一個(gè)條件

Account類中應(yīng)用互斥鎖的的方法如下

withdraw和deposit

然后程序相應(yīng)的修改修改

?第二版Account????public?static?void?main(String[]?args)????{????????System.out.println("Thread?1ttThread?2ttBalance");????????????????ExecutorService?executor?=?Executors.newFixedThreadPool(2);????????executor.execute(new?DepositTask());????????executor.execute(new?WithdrawTask());????????executor.shutdown();????}????????????public?static?class?DepositTask?implements?Runnable????{????????public?void?run()????????{????????????try????????????{????????????????while(true)????????????????{????????????????????account.deposit((int)(Math.random()?*?10)?+?1);????????????????????Thread.sleep(1000);????????????????}????????????}????????????catch(InterruptedException?ex)????????????{????????????????ex.printStackTrace();????????????}????????}????}????????public?static?class?WithdrawTask?implements?Runnable????{????????public?void?run()????????{????????????while(true)????????????{????????????????account.withdraw((int)(Math.random()?*?10)?+?1);????????????}????????}????}

4.客戶端/服務(wù)器的網(wǎng)絡(luò)應(yīng)用

Java中對(duì)socket的使用十分方便,在建立socket連接后就可以使用輸入輸出流的方法實(shí)現(xiàn)數(shù)據(jù)傳輸了。

在實(shí)現(xiàn)基本的GUI后,在服務(wù)器用一個(gè)判斷條件永遠(yuǎn)為true的循環(huán)來監(jiān)聽客戶端的連接請(qǐng)求(Socketsocket=serverSocket.accept();

服務(wù)器通過創(chuàng)建一個(gè)內(nèi)部類(HandleAClient),把客服端的socket傳遞過來執(zhí)行。

HandleAClient類????class?HandleAClient?implements?Runnable????{????????//A?connected?socket????????private?Socket?socket;????????????????????????public?HandleAClient(Socket?socket)????????{????????????this.socket?=?socket;????????}????????????????????????public?void?run()????????{????????????try????????????{????????????????//Create?data?input?and?output?streams????????????????DataInputStream?inputFromClient?=?new?DataInputStream(????????????????????????socket.getInputStream());????????????????DataOutputStream?outputToClient?=?new?DataOutputStream(????????????????????????socket.getOutputStream());????????????????int?order?=?0;????????????????double?amount;????????????????//Continuously?serve?the?client????????????????while(order?!=?4)????????????????{????????????????????//Receive?order,?amount?from?the?client????????????????????order?=?inputFromClient.readInt();????????????????????amount?=?inputFromClient.readDouble();????????????????????????????????????????if(order?==?1)????????????????????{????????????????????????outputToClient.writeDouble(account.getBalance());????????????????????}????????????????????else?if(order?==?2)????????????????????{????????????????????????account.withdraw(amount);????????????????????????outputToClient.writeDouble(account.getBalance());????????????????????}????????????????????else?if(order?==?3)????????????????????{????????????????????????account.deposit(amount);????????????????????????outputToClient.writeDouble(account.getBalance());????????????????????}????????????????????????????????????????jta.append("Order?received?from?client:?"+????????????????????????????order?+?'n');????????????????????jta.append("Balance?is?"?+?account.getBalance()?+?'n');????????????????}????????????}????????????catch(IOException?e)????????????{????????????????System.err.println(e);????????????}????????}????}

而客戶端連接上服務(wù)器后,創(chuàng)建兩個(gè)IO流

? //IOstreams? ? DataOutputStreamtoServer=newDataOutputStream(socket.getOutputStream());? ? DataInputStreamfromServer=newDataInputStream(socket.getInputStream());? ? 即可傳輸order(菜單選項(xiàng))和amount? ? //Sendtheorder,amounttotheserver? ? toServer.writeInt(order);? ? toServer.writeDouble(amount);? ? toServer.flush();? ? 最后再讀取balance? ? balance=fromServer.readDouble();

以上就是長(zhǎng)沙一度軟件培訓(xùn)java培訓(xùn)機(jī)構(gòu)的小編針對(duì)“Java實(shí)戰(zhàn)教程,實(shí)現(xiàn)網(wǎng)絡(luò)之并發(fā)編程”的內(nèi)容進(jìn)行的回答,希望對(duì)大家有所幫助,如有疑問,請(qǐng)?jiān)诰€咨詢,有專業(yè)老師隨時(shí)為你服務(wù)。

培訓(xùn)啦提醒您:交易時(shí)請(qǐng)核實(shí)對(duì)方資質(zhì),對(duì)于過大宣傳或承諾需謹(jǐn)慎!任何要求預(yù)付定金、匯款等方式均存在風(fēng)險(xiǎn),謹(jǐn)防上當(dāng)。