Microsoft PowerPoint - 14Threads.ppt

Similar documents
Chapter 9: Objects and Classes

2009年3月全国计算机等级考试二级Java语言程序设计笔试试题

KillTest 质量更高 服务更好 学习资料 半年免费更新服务

javaexample-02.pdf

Chapter 9: Objects and Classes

untitled


Microsoft Word - 01.DOC

任務二 : 產生 20 個有炸彈的磚塊, 放在隨機的位置編輯 Block 類別的程式碼 import greenfoot.; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) Write a description of class

(TestFailure) JUnit Framework AssertionFailedError JUnit Composite TestSuite Test TestSuite run() run() JUnit

untitled

使 用 Java 语 言 模 拟 保 险 箱 容 量 门 板 厚 度 箱 体 厚 度 属 性 锁 具 类 型 开 保 险 箱 关 保 险 箱 动 作 存 取 款

JavaIO.PDF

Java

Microsoft Word - ch04三校.doc

untitled

Java java.lang.math Java Java.util.Random : ArithmeticException int zero = 0; try { int i= 72 / zero ; }catch (ArithmeticException e ) { // } 0,

软件工程文档编制

chp6.ppt

詞 彙 表 編 號 詞 彙 描 述 1 預 約 人 資 料 中 文 姓 名 英 文 姓 名 身 份 證 字 號 預 約 人 電 話 性 別 2 付 款 資 料 信 用 卡 別 信 用 卡 號 信 用 卡 有 效 日 期 3 住 房 條 件 入 住 日 期 退 房 日 期 人 數 房 間 數 量 入

Microsoft Word - 投影片ch15

KillTest 质量更高 服务更好 学习资料 半年免费更新服务

untitled

chp11.ppt

<4D F736F F D20C8EDC9E82DCFC2CEE7CCE22D3039C9CF>

9, : Java 19., [4 ]. 3 Apla2Java Apla PAR,Apla2Java Apla Java.,Apla,,, 1. 1 Apla Apla A[J ] Get elem (set A) A J A B Intersection(set A,set B) A B A B

EJB-Programming-4-cn.doc

《大话设计模式》第一章

1 Framework.NET Framework Microsoft Windows.NET Framework.NET Framework NOTE.NET NET Framework.NET Framework 2.0 ( 3 ).NET Framework 2.0.NET F

Microsoft PowerPoint - ch02

上海市教育考试院关于印发新修订的

<4D F736F F F696E74202D20332D322E432B2BC3E6CFF2B6D4CFF3B3CCD0F2C9E8BCC6A1AAD6D8D4D8A1A2BCCCB3D0A1A2B6E0CCACBACDBEDBBACF2E707074>

Fun Time (1) What happens in memory? 1 i n t i ; 2 s h o r t j ; 3 double k ; 4 char c = a ; 5 i = 3; j = 2; 6 k = i j ; H.-T. Lin (NTU CSIE) Referenc

主程式 : public class Main3Activity extends AppCompatActivity { ListView listview; // 先整理資料來源,listitem.xml 需要傳入三種資料 : 圖片 狗狗名字 狗狗生日 // 狗狗圖片 int[] pic =new

The Embedded computing platform

javac: 负 责 的 是 编 译 的 部 分, 当 执 行 javac 时, 会 启 动 java 的 编 译 器 程 序 对 指 定 扩 展 名 的.java 文 件 进 行 编 译 生 成 了 jvm 可 以 识 别 的 字 节 码 文 件 也 就 是 class 文 件, 也 就 是 ja

OOP with Java 通知 Project 4: 4 月 19 日晚 9 点

雲端 Cloud Computing 技術指南 運算 應用 平台與架構 10/04/15 11:55:46 INFO 10/04/15 11:55:53 INFO 10/04/15 11:55:56 INFO 10/04/15 11:56:05 INFO 10/04/15 11:56:07 INFO

Microsoft PowerPoint - chap12.ppt

Java Access 5-1 Server Client Client Server Server Client 5-2 DataInputStream Class java.io.datainptstream (extends) FilterInputStream InputStream Obj

内 容 简 介 本 书 是 一 本 关 于 语 言 程 序 设 计 的 教 材, 涵 盖 了 语 言 的 基 本 语 法 和 编 程 技 术, 其 中 包 含 了 作 者 对 语 言 多 年 开 发 经 验 的 总 结, 目 的 是 让 初 学 的 读 者 感 受 到 语 言 的 魅 力, 并 掌

java2d-4.PDF

OOP with Java 通知 Project 4: 4 月 18 日晚 9 点 关于抄袭 没有分数

用手機直接傳值不透過網頁連接, 來當作搖控器控制家電 ( 電視遙控器 ) 按下按鍵發送同時會回傳值來確定是否有送出 問題 :1. 應該是使用了太多 thread 導致在傳值上有問題 2. 一次按很多次按鈕沒辦法即時反應

Microsoft Word - JAVA Programming Language Homework VI_ans.doc

Swing-02.pdf

Microsoft PowerPoint - Java - Lecture 4 Thread & JDBC.ppt

2 2 3 DLight CPU I/O DLight Oracle Solaris (DTrace) C/C++ Solaris DLight DTrace DLight DLight DLight C C++ Fortran CPU I/O DLight AM

提纲 1 2 OS Examples for 3

附录J:Eclipse教程

2 Java 语 言 程 序 设 计 教 程 简 单 性 Java 语 言 的 语 法 与 C 语 言 和 C++ 语 言 很 接 近, 使 得 大 多 数 程 序 员 很 容 易 学 习 和 使 用 Java 另 一 方 面,Java 丢 弃 了 C++ 中 很 少 使 用 的 很 难

1.JasperReport ireport JasperReport ireport JDK JDK JDK JDK ant ant...6

<4D F736F F F696E74202D20B5DA35D5C220D2ECB3A3BACDB6E0CFDFB3CC2E BBCE6C8DDC4A3CABD5D>

untitled

untitled

Microsoft PowerPoint - ch03

1: public class MyOutputStream implements AutoCloseable { 3: public void close() throws IOException { 4: throw new IOException(); 5: } 6:

SDK 概要 使用 Maven 的用户可以从 Maven 库中搜索 "odps-sdk" 获取不同版本的 Java SDK: 包名 odps-sdk-core odps-sdk-commons odps-sdk-udf odps-sdk-mapred odps-sdk-graph 描述 ODPS 基

全国计算机技术与软件专业技术资格(水平)考试

untitled

, 7, Windows,,,, : ,,,, ;,, ( CIP) /,,. : ;, ( 21 ) ISBN : -. TP CIP ( 2005) 1

第7章-并行计算.ppt

新版 明解C++入門編

3.1 num = 3 ch = 'C' 2

OOP with Java 通知 Project 4: 5 月 2 日晚 9 点

<4D F736F F F696E74202D20B8DFBCB6D3C3BBA7BDE7C3E6D3EBB6E0CFDFB3CC2E707074>

Microsoft Word - Learn Objective-C.doc

FY.DOC

EJB-Programming-3.PDF

VHDL(Statements) (Sequential Statement) (Concurrent Statement) VHDL (Architecture)VHDL (PROCESS)(Sub-program) 2

OOP with Java 通知 Project 3: 3 月 29 日晚 9 点 4 月 1 日上课

27 :OPC 45 [4] (Automation Interface Standard), (Costom Interface Standard), OPC 2,,, VB Delphi OPC, OPC C++, OPC OPC OPC, [1] 1 OPC 1.1 OPC OPC(OLE f

untitled

Natural Language Processing, Topic Modeling, Neural Text Generation and Ali Xiaomi

Microsoft Word - 小心翼翼的二十一點N.doc

在 ongodb 中实现强事务

北 风 网 讲 师 原 创 作 品 ---- 仅 供 学 员 内 部 交 流 使 用 前 言 吾 尝 终 日 而 思 矣, 不 如 须 臾 之 所 学 也 ; 吾 尝 跂 而 望 矣, 不 如 登 高 之 博 见 也 登 高 而 招, 臂 非 加 长 也, 而 见

BOOL EnumWindows(WNDENUMPROC lparam); lpenumfunc, LPARAM (Native Interface) PowerBuilder PowerBuilder PBNI 2

untitled

Microsoft Word - 第6章.doc

(6) 要 求 付 款 管 理 员 从 预 订 表 中 查 询 距 预 订 的 会 议 时 间 两 周 内 的 预 定, 根 据 客 户 记 录 给 满 足 条 件 的 客 户 发 送 支 付 余 款 要 求 (7) 支 付 余 款 管 理 员 收 到 客 户 余 款 支 付 的 通 知 后, 检

D C 93 2

Microsoft PowerPoint - P766Ch06.ppt

untitled

Spyder Anaconda Spyder Python Spyder Python Spyder Spyder Spyder 開始 \ 所有程式 \ Anaconda3 (64-bit) \ Spyder Spyder IPython Python IPython Sp

PowerPoint 演示文稿

计 算 机 系 统 应 用 年 第 25 卷 第 4 期 线 程 的 复 用 [2,3]. 通 常 情 况 下, 服 务 器 端 程 序 在 启 动 时 创 建 若 干 数 量 的 线 程 对 象 并 缓 存 起 来, 此 时 它 们 处 于

Microsoft Word - JAVA Programming Language Homework I ans

Learning Java

(京)新登字063号

CC213

untitled

Visual Basic D 3D

mvc

untitled

2009年9月全国计算机等级考试二级Java真题及答案

epub83-1

Strings

多媒體應用 13 新增專案並完成版面配置 <ExMusic01> <activity_main.xml> ImageView ID imgplay ImageView ID imgstop ImageView ID imgfront TextView ID txtsong TextView ID t

使用MapReduce读取XML文件

Transcription:

Threads

Outline Introduction to Threads How to create Thread extend Thread implement Runnable interface Synchronization

What is thread? 定義 : 程式的執行軌跡 Single Thread Multi-Thread 依序執行 int x, y; int z; x = 3; y = x + 4; z = 5; int x, y; x = 3; y = x + 4; int z; z = 5; CPU CPU

Program, Process, Thread 程式 (Program) 儲存於硬碟中的可執行檔稱為 Program 行程 (Process) 載入記憶體中的可執行檔稱為 Process 執行緒 (Thread) Process 中的一個程式碼執行軌跡稱為 Thread, 是電腦中最小的執行單位 Program Process Thread HDD Memory

建立一個執行緒的方法 要建立一個 Thread, 先要建造一個 Thread 物件, 再用 new 產生 Thread 的個體 您 new 幾次, 就有幾個 Thread 建造一個 Thread 物件的方法 : 直接繼承 java.lang.thread 實作 Runnable 介面 事實上 : java.lang.thread 就是一個實作 Runnable 的物件

Thread 物件簡介 與 行為 有關的方法 : void run(): 定義此執行緒的任務 一旦執行緒醒過來後,run() 裡面定義什麼, 它就執行什麼 執行完 run() 後就會死 void start(): 開始執行 Thread 此方法會觸動 run() 函數 boolean isalive(): 傳回此 Thread 是否活動中 static void yield(): 把自己暫停, 先禮讓其它相同優先順序的 Thread 執行 static void sleep(long millis): 讓自己小睡片刻, 經過 millis 微秒 (ms) 後再醒過來 void join(): 停止執行, 等死 void destroy(): 命令 Thread 馬上結束

Thread 物件簡介 與 屬性 有關的方法 : void setname(string name): 為此執行緒取個名字 String getname(): 傳回此執行緒的名字 void setpriority(int newpriority): 設定此執行緒的優先順序 數字越大, 優先順序越高 int getpriority(): 傳回此執行緒的優先順序 String tostring(): 傳回此執行緒的名稱, 優先順序, 及所屬群組 Thread 物件內的常數 static int MAX_PRIORITY: 最高優先順序值 static int MIN_PRIORITY: 最低優先順序值 static int NORM_PRIORITY: 預設優先順序值

Thread 物件簡介 七大建構元 Thread() Thread(String name) Thread(Runnable target) Thread(Runnable target, String name) Thread(ThreadGroup group, String name) Thread(ThreadGroup group, Runnable target) Thread(ThreadGroup group, Runnable target, String name);

Thread 物件簡介 建構元參數介紹 : String name: 此 Thread 的名字 如果沒有提供, 預設的名字是 Thread-n, 其中 n 是一個整數 Runnable target: 使用其它類別內的 run() 函式作為此類別的 run() 函式 ThreadGroup group: 指定此 Thread 應隸屬於哪一個 Thread Group

繼承 Thread 的範例 class Horse extends Thread { final int MAX_DISTANCE = 600; int RaceDistance = 400; int CurrentDistance = 0; long RaceTime = 0L; // Constructors public Horse() { super(); public Horse(String name) { super(name); public Horse(String name, int distance) { super(name); RaceDistance = (distance < MAX_DISTANCE)? distance: MAX_DISTANCE;

繼承 Thread 的範例 public void run() { long begin = 0L, end = 0L; begin = System.currentTimeMillis(); while (CurrentDistance <= RaceDistance) { CurrentDistance += Math.floor(Math.random() * 10); System.out.println(getName() + ": " + CurrentDistance); try { sleep((long)(math.random() * 1000)); catch (InterruptedException e) { end = System.currentTimeMillis(); RaceTime = end - begin; public int getcurrentdistance() { return CurrentDistance; public long getracetime() { return RaceTime;

繼承 Thread 的範例 public class RaceHorse { public static void main(string[] args) { Horse Rubby = new Horse("Rubby", 40); Horse Lisa = new Horse("Lisa", 40); Rubby.start(); Lisa.start(); while (Rubby.isAlive() Lisa.isAlive()) { // Do nothing, just wait for the end. if (Rubby.getRaceTime() < Lisa.getRaceTime()) System.out.println("Rubby win!! Record: " + Rubby.getRaceTime() + " ms"); else if (Rubby.getRaceTime() > Lisa.getRaceTime()) System.out.println("Lisa win!! Record: " + Lisa.getRaceTime() + " ms"); else System.out.println("Deuce! Record: " + Rubby.getRaceTime());

Runnable 介面簡介 用途 自訂 Thread 時, 除了繼承 java.lang.thread, 也可實作 Runnable 介面 使用時機 當您自訂的類別已經繼承其它類別, 卻又要變成一個 Thread 物件時 方法 : void run() Runnable 內唯一需要程式師實作的方法

實作 Runnable 介面的範例 class RunHorse extends Thread {. public void run() { long begin = 0L, end = 0L; begin = System.currentTimeMillis(); while (CurrentDistance <= RaceDistance) { CurrentDistance += Math.floor(Math.random() * 10); System.out.println(getName() + ": " + CurrentDistance); try { sleep((long)(math.random() * 1000)); catch (InterruptedException e) { end = System.currentTimeMillis(); RaceTime = end - begin;. 將原先 class Horse 中的 System.out.println 刪除, 改名為 class RunHorse 重編譯即可

實作 Runnable 介面的範例 import java.applet.*; import java.awt.*; public class RunningHorse extends Applet implements Runnable { private Thread horsethread = null; int totalhorses; int racedistance; RunHorse[] TheHorse; Image[] imghorse; AudioClip MyAudio; int thewinner; private boolean bracefinished = false; private String WinnerMsg = "";

實作 Runnable 介面的範例 public void init() { totalhorses = Integer.parseInt(getParameter("TotalHorses")); racedistance = Integer.parseInt(getParameter("RaceDistance")); horsethread = new Thread(this, "RunningHorse"); horsethread.setpriority(thread.norm_priority + 5); TheHorse = new RunHorse[totalHorses]; imghorse = new Image[totalHorses]; for (int i=0; i<totalhorses; i++) { TheHorse[i] = new RunHorse(getParameter("Horse" + i), racedistance); imghorse[i] = getimage(getdocumentbase(), "Images/Horse" + i + ".gif"); MyAudio = getaudioclip(getdocumentbase(), "Audio/RunHorse.au");

實作 Runnable 介面的範例 public void run() { boolean bsomeonealive; do { repaint(); bsomeonealive = false; for (int i=0; i<totalhorses; i++) bsomeonealive = bsomeonealive TheHorse[i].isAlive(); while (bsomeonealive); thewinner = 0; for (int i=0; i<totalhorses; i++) { if (TheHorse[theWinner].getRaceTime() > TheHorse[i].getRaceTime()) thewinner = i; WinnerMsg = "The Winner is " + TheHorse[theWinner].getName(); bracefinished = true; MyAudio.stop();

實作 Runnable 介面的範例 public boolean mousedown(event evt, int x, int y) { // When mouse click, enable all threads for (int i=0; i<totalhorses; i++) if (! TheHorse[i].isAlive()) TheHorse[i].start(); if (! horsethread.isalive()) horsethread.start(); MyAudio.loop(); return true;

實作 Runnable 介面的範例 public void paint(graphics g) { // Show the message on top if (horsethread.isalive()) g.drawstring("go! Go! Racing Horses...", 5, 25); else g.drawstring("reload the page and click to play...", 5, 25); // Draw the racing field g.setcolor(color.yellow); g.fillrect(0, 100, racedistance, totalhorses * 100);

實作 Runnable 介面的範例 // Draw the Horses, name and line int i; int ThisX, ThisY; g.setcolor(color.black); for (i=0; i<totalhorses; i++) { ThisX = TheHorse[i].getCurrentDistance(); ThisY = (i+1)*100; g.drawimage(imghorse[i], ThisX, ThisY, this); g.drawline(0, ThisY+50, ThisX, ThisY+50); g.drawstring(thehorse[i].getname(), racedistance+110, ThisY+50);

實作 Runnable 介面的範例 if (bracefinished) { g.drawstring(winnermsg, 5, 95); for (i=0; i<totalhorses; i++) { g.drawstring(string.valueof(thehorse[i].getracetime()), racedistance+110, (i+1)*100+75);

執行緒同步問題 所謂 執行緒同步問題 是指兩個執行緒同時存取一個共用變數時, 所會發生的問題 : 王先生 $10000 王太太 $10000 $10000 - $1000 - $9000 $9000 $1000 $1000 $9000 提領 $1000 提領 $1000 提領 $9000

執行緒同步問題 王先生 $10000 王太太 $10000 $10000 問題就出在這裡

執行緒同步問題 解決方法 :Lock Wait - Notify 王先生 $10000 王太太 $10000 Lock Wait - $1000 $9000 $9000 Notify $9000

執行緒同步問題 Java 的解決方法 : Lock: 使用 synchronized 保留字 Wait: 使用 Wait() 函數 Notify: 使用 Notify() 或 NotifyAll()

未經過同步保護的例子 public class MyBank implements Runnable { int balance = 100000; public static void main(string[] args) { MyBank bank = new MyBank(); Thread Husbon = new Thread(bank, "Mr. Wang"); Thread Wife = new Thread(bank, "Mrs. Wang"); Husbon.start(); Wife.start();

未經過同步保護的例子 public void run() { String name = Thread.currentThread().getName(); for(int i=0; i<10; i++) { balance -= 1000; System.out.println(name + ": " + balance); try { Thread.currentThread().sleep((long)(Math.random()*500)); catch(interruptedexception e) {

經過同步保護的例子 public class MyBank implements Runnable { int balance = 100000; public static void main(string[] args) { MyBank bank = new MyBank(); Thread Husbon = new Thread(bank, "Mr. Wang"); Thread Wife = new Thread(bank, "Mrs. Wang"); Husbon.start(); Wife.start();

經過同步保護的例子 public void run() { String name = Thread.currentThread().getName(); for(int i=0; i<10; i++) { synchronized (this) { balance -= 1000; // this block allow only one thread System.out.println(name + ": " + balance); try { Thread.currentThread().sleep((long)(Math.random()*500)); catch(interruptedexception e) {

另一種同步保護的寫法 public class MyBank implements Runnable { int balance = 100000; public static void main(string[] args) { MyBank bank = new MyBank(); Thread Husbon = new Thread(bank, "Mr. Wang"); Thread Wife = new Thread(bank, "Mrs. Wang"); Husbon.start(); Wife.start();

另一種同步保護的寫法 public void run() { String name = Thread.currentThread().getName(); for(int i=0; i<10; i++) { withdraw(1000); System.out.println(name + ": " + balance); try { Thread.currentThread().sleep((long)(Math.random()*500)); catch(interruptedexception e) { protected synchronized void withdraw(int money) { balance -= money;