java结束全部操作代码_Java基本的线程操作(附代码)
啦啦啦啦,從頭整理一遍java并發的內容.開始是基本的線程操作
線程狀態切換:
新建線程:
@Testpublic voidnewTread(){
Thread t1= new Thread(newRunnable() {
@Overridepublic voidrun() {
System.out.println("ok...");
}
});
t1.start();
}
終止線程:
Thread.stop() 不推薦使用。它會釋放所有monitor
中斷線程:
public void Thread.interrupt() // 中斷線程
public boolean Thread.isInterrupted() // 判斷是否被中斷
public static boolean Thread.interrupted() // 判斷是否被中斷,并清除當前中斷狀態
public voidrun(){while(true){if(Thread.currentThread().isInterrupted()){
System.out.println("Interruted!");break;
}
Thread.yield();
}
}
t1.start();
t1.interrupt();
sleep:
public static native void sleep(long millis) throws InterruptedException
public voidrun(){while(true){if(Thread.currentThread().isInterrupted()){
System.out.println("Interruted!");break;
}try{
Thread.sleep(2000);
}catch(InterruptedException e) {
System.out.println("Interruted When Sleep");//設置中斷狀態,拋出異常后會清除中斷標記位
Thread.currentThread().interrupt();
}
Thread.yield();
}
}
掛起 and 繼續執行:
– suspend()不會釋放鎖
– 如果加鎖發生在resume()之前 ,則死鎖發生
等待線程結束(join)和謙讓(yeild)
public final void join() throws InterruptedException
public final synchronized void join(long millis) throws InterruptedException
join的本質
while (isAlive()) {
wait(0);
}
線程執行完畢后,系統會調用notifyAll();
public classJoinMain {public volatile static int i=0;public static class AddThread extendsThread{
@Overridepublic voidrun() {for(i=0;i<10000000;i++);
}
}public static void main(String[] args) throwsInterruptedException {
AddThread at=newAddThread();
at.start();
at.join();
System.out.println(i);
}
}
synchronized
– 指定加鎖對象:對給定對象加鎖,進入同步代碼前要獲得給定對象的鎖。
– 直接作用于實例方法:相當于對當前實例加鎖,進入同步代碼前要獲得當前實例的鎖。
– 直接作用于靜態方法:相當于對當前類加鎖,進入同步代碼前要獲得當前類的鎖。
? Object.wait() Obejct.notify()
總結
以上是生活随笔為你收集整理的java结束全部操作代码_Java基本的线程操作(附代码)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java后台面试自我介绍_java腾讯远
- 下一篇: 描述java源程序构成_2.1 Java