




已閱讀5頁,還剩8頁未讀, 繼續(xù)免費閱讀
版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)
文檔簡介
尚學(xué)堂科技_馬士兵_JAVA視頻教程_J2SE_5.0_第09章_線程 聽課筆記 2010-4-2 20:16:34 by LoveXForce第九章 Java多線程機制線程基本概念 Runnable線程類接口線程創(chuàng)建和啟動線程的調(diào)度好優(yōu)先級線程的狀態(tài)控制 sleep join yield 線程同步synchronized wait notify/notifyAll一、 線程基本概 :1進程:一個獨立程序的每一次運行稱為一個進程。執(zhí)行進程是指進程里面主線程mian方法開始執(zhí)行了(靜態(tài)概念)。機器上運行的都是線程2線程是一個程序不同的執(zhí)行路徑 是一個程序內(nèi)部的順序控制流)main方法:一個主線程,主分支3一個時間點上一個CPU只能有一個線程執(zhí)行進程與線程區(qū)別每個進程都有獨立的代碼和數(shù)據(jù)空間,進程間的切換會有很大開銷。線程可以看成輕量級的進程 同一類線程共享代碼和數(shù)據(jù)空間,每個線程有獨立的運行棧個程序計數(shù)器,線程切換開銷小。多線程:在操作系統(tǒng)中能同時運行多個任務(wù)(程序)。多線程:在同一個應(yīng)用程序中有多個順序流同時執(zhí)行。二、 線程的創(chuàng)建和啟動1實現(xiàn)Runnable接口(常用)設(shè)計一個實現(xiàn)Runable接口的類,根據(jù)需要重寫run方法;建立該類的對象,以此對象為參數(shù)建立Thread類的對象;調(diào)用Thread類對象start方法啟動線程,將執(zhí)行權(quán)轉(zhuǎn)交到run方法。2繼承Thread類 定義一個從Thread類繼承的子類并重寫其run方法然后生成該類的對象,調(diào)用Thread類對象start方法啟動線程說明:Runnable接口 java.lang.Runnable Java多線程機制的一個重要部分,實際上它只有一個run()方法 Thread類實現(xiàn)了Runnable接口,相對于Thread類,它更適合于多個線程處理同一資源 實現(xiàn)Runnable接口的類的對象可以用來創(chuàng)建線程,這時start方法啟動此線程就會在此線程上運行run()方法 在編寫復(fù)雜程序時相關(guān)的類可能已經(jīng)繼承了某個基類,而Java不支持多繼承,在這種情況下,便需要通過實現(xiàn)Runnable接口來生成多線程Thread類 java.lang.Thread 在Java程序中創(chuàng)建多線程的方法之一是繼承Thread類 封裝了Java程序中一個線程對象需要擁有的屬性和方法 從Thread類派生一個子類,并創(chuàng)建這個子類的對象,就可以產(chǎn)生一個新的線程。這個子類應(yīng)該重寫Thread類的run方法,在run方法中寫入需要在新線程中執(zhí)行的語句段。這個子類的對象需要調(diào)用start方法來啟動,新線程將自動進入run方法。原線程將同時繼續(xù)往下執(zhí)行 Thread類直接繼承了Object類,并實現(xiàn)了Runnable接口。它位于java.lang包中,因而程序開頭不用import任何包就可直接使用例子:ThreadTestThread1.java 開始使用Eclipse1實現(xiàn)Runnable接口(多線程程序交替執(zhí)行.多態(tài)(接口,常用))package Thread;public class TestThread1 public static void main(String args) Runner r = new Runner();Thread t = new Thread(r);/主線程;t.start();/啟動分支線程for(int i=0; i100; i+) System.out.println(Main Thread:- + i);class Runner implements Runnable public void run() /線程運行體;for(int i=0; i100; i+) System.out.println(Runner1 : + i);2 一般程序先執(zhí)行子線程,再執(zhí)行主線程(方法調(diào)用)package Thread;public class TestThread1_1 public static void main(String args) Runner1 r = new Runner1();r.run();for(int i=0; i100; i+) System.out.println(Main Thread:- + i);class Runner1 implements Runnable public void run() for(int i=0; i100; i+) System.out.println(Runner1 : + i);3繼承Thread類(繼承,不常用)package Thread;public class TestThread1_2public static void main(String arg)Runner1_2 r = new Runner1_2();r.start();for (int i = 0 ;i = 100; i+)System.out.println(Main Thread:!+i);class Runner1_2 extends Threadpublic void run()for (int i = 0 ;i = 100; i+)System.out.println(Runner2:!+i);2010-4-2 21:04:16 2010-4-14 16:28:59三、 線程狀態(tài)轉(zhuǎn)換四、 線程控制基本方法Sleep/Join/Yield方法 Sleep/Join(需要捕獲異常)例子1 Thread/TestInterrupt.Java (線程結(jié)束的方式)package Thread;import java.util.*;public class TestInterrupt public static void main(String arg)MyThread thread = new MyThread();thread.start();tryThread.sleep(10000);/主線程睡眠catch(InterruptedException e)errupt();/中斷線程。class MyThread extends Threadboolean flag = true;public void run()/重寫的方法不能拋出不必被重寫方法不同的方法,此處不能寫throws InterruptedExceptionwhile(flag)System.out.println(-+ new Date()+-);trysleep(1000);catch(InterruptedException e)/捕獲拋出的異常return;/停止例子2 Thread/ TestJoin.Java (線程合并方式)package Thread;public class TestJoin public static void main(String args) MyThread2 t1 = new MyThread2(abcde); t1.start();/啟動分支線程 try t1.join();/把T1分支線程合并到當前線程 catch (InterruptedException e) for(int i=1;i=10;i+) System.out.println(i am main thread); class MyThread2 extends Thread MyThread2(String s) super(s); public void run() for(int i =1;i=10;i+) System.out.println(i am +getName(); try sleep(1000); catch (InterruptedException e) return; 例子3 Thread/ TestYield.Java (讓出Cup)package Thread;public class TestYield public static void main(String args) MyThread3 t1 = new MyThread3(t1); MyThread3 t2 = new MyThread3(t2); t1.start(); t2.start(); class MyThread3 extends Thread MyThread3(String s)super(s); public void run() for(int i =1;i=100;i+) System.out.println(getName()+: +i); if(i%10=0) yield(); 五、 線程優(yōu)先級 Priority例子 Thread/ TestPriority.Javapackage Thread;public class TestPriority public static void main(String args) Thread t1 = new Thread(new T1();Thread t2 = new Thread(new T2();t1.setPriority(Thread.NORM_PRIORITY + 3);/提高優(yōu)先級t1.start();t2.start();class T1 implements Runnable public void run() for(int i=0; i1000; i+) System.out.println(T1: + i);class T2 implements Runnable public void run() for(int i=0; i1000; i+) System.out.println(-T2: + i);2010年4月14日21:40:41 2010-4-15 16:23:44六、 例子 TestThread2-6TestThread2一個線程類可以啟動兩個線程package Thread;public class TestThread2 /一個線程類可以啟動兩個線程public static void main(String args) Runner2 r = new Runner2();Thread t1 = new Thread(r);Thread t2 = new Thread(r);t1.start();t2.start();class Runner2 implements Runnable public void run() for(int i=0; i30; i+) System.out.println(No. + i);正常停止線程TestThread4package Thread;public class TestThread4 /怎么正常停止線程public static void main(String args)Runner4 r = new Runner4(); Thread t = new Thread(r); t.start(); for(int i=0;i0) System.out.println(in thread main i= + i); System.out.println(Thread main is over); r.shutDown(); /t.stop(); class Runner4 implements Runnable private boolean flag=true; public void run() int i = 0;while (flag=true) System.out.print( + i+); public void shutDown() flag = false; TestThread6 isAlivepackage Thread;public class TestThread6 public static void main(String args)Thread t = new Runner6(); t.start();for(int i=0; i50; i+) System.out.println(MainThread: + i); class Runner6 extends Thread public void run() System.out.println(Thread.currentThread().isAlive();for(int i=0;i50;i+) System.out.println(SubThread: + i);七、 線程同步引入:兩人同時取同一賬戶的錢兩個線程訪問同一資源,進程之間協(xié)調(diào)的問題解決:在進程訪問獨占資源時先鎖定再訪問 synchronized 最好只鎖定一個對象加鎖過程中:一個方法做了同步(加鎖)另一個方法沒有做同步,別的線程可以訪問沒做同步的方法,并且能影響已經(jīng)同步的方法,要保護需要的同步的對象,必須對要訪問的對象所有方法要仔細考慮加不加同步,加同步效率變低,不加同步有可能產(chǎn)生數(shù)據(jù)不一致的后果讀寫兩方法,寫的方法加鎖。兩個方法都改了同一個值,兩個方法都應(yīng)該加同步TsetSync.javapackage Thread;public class TestSync implements Runnable Timer timer = new Timer(); public static void main(String args) TestSync test = new TestSync(); Thread t1 = new Thread(test); Thread t2 = new Thread(test); t1.setName(t1); t2.setName(t2); t1.start(); t2.start(); public void run() timer.add(Thread.currentThread().getName();/拿到當前線程的名字 class Timer private static int num = 0; public void add(String name) /public synchronized void add(String name) /synchronized 鎖定關(guān)鍵字 /synchronized (this) /鎖定 num +; try Thread.sleep(1); /讓線程睡眠,給另一個線程執(zhí)行的機會,更容易看到xia catch (InterruptedException e) System.out.println(name+, 你是第+num+個使用timer的線程); / t2, 你是第2個使用timer的線程t1, 你是第2個使用timer的線程堆內(nèi)存:test對象testtimertimer對象t1t2問題出現(xiàn)在線程執(zhí)行方法時被另一個線程打斷了.執(zhí)行:num +;.System.out.println(name+, 你是第+num+個使用timer的線程);兩句話時被另個進程打斷死鎖 07_線程同步_3.aviThread/TestDeadLock.java兩個線程鎖定了互斥的對象package Thread;/一個線程類模擬兩個線程。用flag區(qū)分public class TestDeadLock implements Runnable public int flag = 1;static Object o1 = new Object(), o2 = new Object();public void run() System.out.println(flag= + flag);if(flag = 1) synchronized(o1) /鎖定o1try Thread.sleep(500); catch (Exception e) e.printStackTrace();synchronized(o2) /鎖定o2System.out.println(1);if(flag = 0) synchronized(o2) /鎖定o2try Thread.sleep(500); catch (Exception e) e.printStackTrace();synchronized(o1) /鎖定o1System.out.println(0);public static void main(String args) TestDeadLock td1 = new TestDeadLock();TestDeadLock td2 = new TestDeadLock();td1.flag = 1;td2.flag = 0;Thread t1 = new Thread(td1);Thread t2 = new Thread(td2);t1.start();t2.start();一道面試題:08_線程同步_4.Avi.當m1()方法執(zhí)行的過程中,另外的線程能執(zhí)行m2()package Thread;public class TT implements Runnable int b = 100;public synchronized void m1() throws Exceptionb = 1000;Thread.sleep(5000);System.out.println(b = + b);public void m2() System.out.println(b);public void run() try m1(); catch(Exception e) e.printStackTrace();public static void main(String args) throws Exception TT tt = new TT();Thread t = new Thread(tt);t.start();Thread.sleep(1000);tt.m2();結(jié)果:1000b = 1000八、 生產(chǎn)者消費者問題 11_線程同步_7_生產(chǎn)者消費者問題.avi XXX.wait() 讓當前訪問這個線程等待,此時這個線程的鎖不存在了XXXX.notify() 喚醒在此對象監(jiān)視器上等待的單個線程。一個wait()對應(yīng)一個notify()package Thread;public class ProducerConsumer public static void main(String args) SyncStack ss = new SyncStack();Producer p = new Producer(ss);Consumer c = new Consumer(ss);new Thread(p).start();new Thread(p).start();new Thread(p).start();new Thread(c).start();class WoTou int id; WoTou(int id) this.id = id;public String toString() return WoTou : + id;class SyncStack int index = 0;WoTou arrWT = new WoTou6;public synchronized void push(WoTou wt) while(index = arrWT.length) try this.wait(); catch (InterruptedException e) e.printStackTrace();this.notifyAll();/ 喚醒arrWTindex = wt;index +;public synchronized WoTou pop() while(index = 0) try this.wait(); catch (InterruptedExc
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 基層醫(yī)療衛(wèi)生機構(gòu)信息化建設(shè)中的醫(yī)療信息化與疾病預(yù)防控制報告
- 月嫂技能培訓(xùn)課件
- 新零售背景下便利店智能化供應(yīng)鏈金融創(chuàng)新報告
- 薄膜干涉題目及答案
- 安全質(zhì)量培訓(xùn)試題及答案
- 咖啡連鎖品牌擴張戰(zhàn)略布局報告:2025年市場拓展與品牌戰(zhàn)略優(yōu)化方案創(chuàng)新
- 安全護理的試題及答案
- 單位音樂培訓(xùn)課件模板
- 安檢排爆培訓(xùn)課件
- cpa培訓(xùn)課件下載
- 新生兒病區(qū)??评碚摽荚囶}庫
- 健康評估咳嗽咳痰課件
- 白酒酒店合作合同協(xié)議書
- 中國融通農(nóng)業(yè)發(fā)展有限集團有限公司招聘筆試題庫2025
- 實驗室通風(fēng)系統(tǒng)工程施工方案
- 2024淮安市專業(yè)技術(shù)人員繼續(xù)教育試題參考答案
- 成人體外膜肺氧合循環(huán)輔助護理專家共識-解讀與臨床應(yīng)用(2025版)
- 慢性活動性EB病毒病診治專家共識(2025版)解讀
- 2025年入團考試常見問題及試題答案
- 績效考核合同協(xié)議書范本
- 2025年公路水運工程重大事故隱患判定標準深度解析
評論
0/150
提交評論