java 多線程中的wait方法的詳解


java多線程中的實現方式存在兩種:

方式一:使用繼承方式

例如:

 1 PersonTest extends Thread{
 2 
 3 String name;
 4 
 5 public PersonTest(String name){
 6 
 7 super(name);
 8 
 9 this.name=name
10 
11 }
12 
13 }

 

 

方式二:使用實現接口的方式

例如:

 1 public PersonT implements Runnable{
 2 public void run(){
 3 //此處為執行的代碼
 4 }
 5 }
 6 //實例化方式
 7 public jacktest{
 8 public static void main(String[] args){
 9 PersonT t=new PersonT();
10 Thread tt=new Thread(t,"線程1");
11 tt.start();
12 }
13 }

 

wait使用方式:

package TestThread.ThreadSynchronized.TestInterruptedException;

public class InterruptDemo {
    public static void main(String[] args) {
        TestWait t = new TestWait("線程1");
        TestWait t1 = new TestWait("線程2");
        t.start();
        t1.start();
    }
}

class TestWait extends Thread {
    String name;

    public TestWait(String name) {
        super(name);
        this.name = name;
    }

    public synchronized void run() {
        for (int i = 0; i < 5; i++) {
            if (i == 4) {
                try {
                    // 等待之后立即釋放當前鎖,並且進入等待池中等待喚醒
                    // 當等待池中的線程被喚醒后,再次執行此語句之后的語句
                    this.wait();
                    System.out.println(Thread.currentThread().getName() + ":我還沒有被執行到!");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(Thread.currentThread().getName() + ":當前的值為--->" + i);
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM