執行緒和程序小知識(二)

2021-09-29 20:35:45 字數 3685 閱讀 8074

執行緒是程序內的執行單元

`thread1.stop();`   不推薦使用,它會釋放所有的monitor  太暴力,一致性很難得到保證。

`thread1.interrupt();` //void 中斷執行緒

`thread1.isinterrupted();` //boolean 判斷是否被中斷

`thread1.interrupted();` //static boolean 判斷是否被中斷,並清除當前中斷狀態

不推薦使用

public

class

test

@override

public

void

run()}

}public

static

void

main

(string[

] args)

throws interruptedexception

}

/**

* @author: baimh

* @date: 2019/9/25 17:39

*/public

class

test

catch

(interruptedexception e)}}

}public

static

void

main

(string[

] args)

}

高優先順序的執行緒更容易在競爭中獲勝高優先順序有更高的概率搶占到資源

public

class

test}}

}}public

static

class

lowpriority

extends

thread}}

}}public

static

void

main

(string[

] args)

}

/**

* @author: baimh

* 指定加鎖物件:對給定物件加鎖,進入同步**前要獲得給定物件的鎖。

*/public

class

test

implements

runnable}}

public

static

void

main

(string[

] args)

throws interruptedexception

}

/**

* @author: baimh

* 直接作用於例項方法:相當於對當前例項加鎖,進入同步**前要獲得當前例項的鎖。

*/public

class

test

implements

runnable

@override

public

void

run()}

public

static

void

main

(string[

] args)

throws interruptedexception

}

/**

* @author: baimh

* 直接作用於例項方法

* 錯誤的加鎖方式,必須加在同乙個例項上邊,加鎖才會有效

*/public

class

test

implements

runnable

@override

public

void

run()}

public

static

void

main

(string[

] args)

throws interruptedexception

}

/**

* @author: baimh

* 直接作用於靜態方法:相當於對當前類加鎖,進入同步**前要獲得當前類的鎖。

*/public

class

test

implements

runnable

@override

public

void

run()}

public

static

void

main

(string[

] args)

throws interruptedexception

}

public

class

test

catch

(interruptedexception e)

system.out.

println

(system.

currenttimemillis()

+": t1 end!");

}}}public

static

class

t2extends

thread

catch

(interruptedexception e)}}

}public

static

void

main

(string[

] args)

}

//執行結果

1574403575818

: t1 start!

1574403575818

: t1 wait for object

1574403575818

: t2 start! notify one thread

1574403575819

: t2 end!

1574403577820

: t1 end!

程序和執行緒相關小知識

幾個基本概念 pcb process control block,程序控制塊的 程序映像 由資料段,程式段和pcb三部分組成。程序和執行緒的區別 a.排程 程序作為擁有資源的基本單位,執行緒作為排程和分派的基本單位。b.併發性 程序和執行緒皆可併發執行,乙個程序中的多個執行緒也可併發執行,提高了系統...

執行緒程序知識框架

個人部落格,歡迎來撩 fangzengye.com 1.動態性 具有建立 就緒 阻塞 執行 結束的狀態 2.併發性 指多個程式能在乙個時間段內同時執行 3.獨立性 獨立執行 獨立獲取資源 4.非同步性 指各自獨立 不可預知的速度向前推進1.就緒 2.執行 3.阻塞 4.掛起 4.1使用者需要 4.2...

執行緒和程序

標準的定義是 程序是執行緒的容器,乙個程序可於乙個或者多個執行緒,它是系統分配資源的基本單位 同乙個程序下,執行緒共享位址空降 已經開啟的檔案 訊號處理函式 報警訊號和其他,執行緒自己只保留程式計數器和棧。但是很遺憾的,這個只是教科書上的定義,實際情況是每個作業系統實現的作業系統特性不同,實現的方法...