標籤:專案檔 err nbsp 主函數 static notifyall start notify art
想要實現線程可以繼承Thread也可以實現介面runnable,在類中重寫 run()方法在主函數調用start方法就可以開闢線程。
對於java對象都有一個wait()和notify()、notifyAll()方法這是線程對這個對象資源的使用順序的調和,在調用這些方法錢必須先使用同步鎖synchronized(對象)將方法用在鎖的裡面就可以了。
一般來說,調用start()方法後run內的內容結束該線程就自動結束了,但是如果裡面有線程還在等待某對象則通過人物管理器的詳細資料可以看到該進程一直存在,並且導致這個專案檔在myEclipse中無法刪除,這時只要在任務管理中的詳細資料裡將這個程式的進程強制關閉就行了。
下面是我做測試的代碼:
public class MyThread extends Thread{
public String li="li123";
public MyThread(String obj){
super(obj);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
MyThread a=new MyThread("jiangzhongxi");
NotifyThread b=a.new NotifyThread();
a.start();
b.start();
}
public void run(){
System.out.println("建立一個線程1使用li對象");
try {
System.out.println("線程1使用li對象4秒");
sleep(4000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized(li){
li.notifyAll();
System.out.println("該線程1對li對象的使用完畢,已經通知其餘所有等待的線程"+li.intern());
}
}
class NotifyThread extends Thread {
public void run() {
System.out.println("建立一個線程2使用li對象");
synchronized (li) {
try {
System.out.println("線程2等待!li對象");
li.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("線程2結束!");
}
};
}
java 線程的簡單理解