線程的2中創(chuàng)建方式
創(chuàng)建線程的第一種方式:繼承 Thread寇壳,由子類重寫run方法
class Th1
{
? ? public static void main(String[] args)
? ? {
? ? ? ? ? ?Thread1 th = new Thread1();
? ? ? ? ? ? th.start()
? ? }
}
class Thread1 extends Thread
{
? ? public void run()
? ? {
? ? // 線程執(zhí)行內(nèi)容
? ? }
}
線程狀態(tài):
新建:start()
運(yùn)行:具備執(zhí)行資格由驹,同事具備執(zhí)行權(quán)
凍結(jié):sleep(time), wait() -- notify()喚醒珍坊, 線程釋放了執(zhí)行權(quán)社露,同事釋放執(zhí)行資格
臨時(shí)阻塞狀態(tài):線程具備cpu的執(zhí)行資格猜嘱,沒有cpu的執(zhí)行權(quán)
消亡:Stop()
創(chuàng)建多線程的第二種方式:實(shí)現(xiàn)一個(gè)接口 Runable
class Th2
{
? ? public static void main(String[] args)
? ? {
? ? ? ? Thread2 t = new Thread2();
? ? ? ? Thread th = new Thread(t);
? ? ? ? th.start();
? ? }
}
public Thread2 implements Runnable
{
? ? public vlid run(){
// 線程執(zhí)行內(nèi)容
? ? }
}
多線程安全問題的原因:
一個(gè)線程在執(zhí)行多條語(yǔ)句的時(shí)候,并預(yù)算同一個(gè)數(shù)據(jù)時(shí)纫普,在執(zhí)行過程中阅悍,其他線程參與進(jìn)來,并操作了這個(gè)數(shù)據(jù)昨稼,導(dǎo)致了錯(cuò)誤數(shù)據(jù)的產(chǎn)生节视。
解決安全問題的原理:
只要將操作的共享數(shù)據(jù)的語(yǔ)句在某一時(shí)段讓一個(gè)線程執(zhí)行完,在執(zhí)行過程中假栓,其他西城不能執(zhí)行就可以了
JAVA中提供一個(gè)解決方案方式:同步代碼塊
格式:
Synchroized(對(duì)象) { 對(duì)任意對(duì)象都可以寻行,這個(gè)對(duì)象就是縮
需要同步的代碼
}
wait 和 sleep 的區(qū)別:
wait 可以指定時(shí)間,也可以不指定時(shí)間但指。不指定時(shí)間寡痰,只能由notify或者notifyAll來喚醒
sleep:必須指定時(shí)間抗楔,時(shí)間到自動(dòng)從凍結(jié)狀態(tài)轉(zhuǎn)成運(yùn)行狀態(tài)
wait : 線程會(huì)釋放執(zhí)行權(quán),而且線程會(huì)釋放鎖
sleep:線程會(huì)釋放執(zhí)行權(quán)拦坠,但是不會(huì)釋放鎖