線程之間的通信

線程間通信(線程與線程間進行通信)
線程池:存放等待中的線程的一片空間

 等待喚醒機制:
 wait();       讓一個線程處於等待,等待線程釋放執行權回到線程池當中等待
 notify();     隨機喚醒線程池當中的一個線程
 notifyAll();  喚醒線程池當中所有的線程   

 以上方法都是對象上的方法,都是鎖對象上的方法-->鎖就相當於是監視該線程上的一個監視器

//學生類

class student {
    String name;
    String sex;
}

// 輸入類

class Input implements Runnable {
    private int count;
    private student s;

public Input(student s) {
    this.s = s;
}

@Override
public void run() {
    while (true) {
        synchronized (student.class) {   // (s)           反正都是操作同一對象 即也可以 以鎖爲對象
            if (count % 2 == 0) {
                s.name = "張三";
                s.sex = "男";
            } else {
                s.name = "lisi";
                s.sex = "women";
            }
            count++;
        }
    }
}

}

// 輸出類

class Output implements Runnable {
    private student s;

public Output(student s) {
    this.s = s;
}

@Override
public void run() {
    while (true) {
        synchronized (student.class) {   // (s)           反正都是操作同一對象 即也可以 以鎖爲對象
            System.out.println(s.name + ":" + s.sex);
        }
    }
}

}

// 線程測試類

public class ThreadDemo03 {
    public static void main(String[] args) {
        student s = new student();
        Input i = new Input(s);
        Output o = new Output(s);
        Thread t1 = new Thread(i);
        Thread t2 = new Thread(o);
        t1.start();
        t2.start();
    }
} 

經過優化之後的喚醒機制

//學生類

class Student{
    private String name;
    private String sex;

private boolean flag = false;

public void set(String name,String sex){
    synchronized(this){
        if(flag)//如果標記爲true,就代表輸入已完成,輸入任務就可以等待
            try {wait();} catch (InterruptedException e) {}
        this.name = name;
        this.sex = sex;
        flag = true;
        notify();
    }       
}

public void show(){
    synchronized(this){
        if(!flag)
            try {wait();} catch (InterruptedException e) {}
        System.out.println(this.name  + " : " + this.sex);
        flag = false;
        notify();
    }
}

}

//輸入類

class Input implements Runnable{
    private Student s;
    private int count;

public Input(Student s) {
    this.s = s;
}
@Override
public void run() {
    //要執行的輸入任務
    while(true){
        if(count % 2 == 0){
            s.set("張三", "男");
        }else{
            s.set("lisi", "woman");
        }
        count++;
    }
}

}

//輸出類

class Output implements Runnable{
    private Student s;
    public Output(Student s) {
    this.s = s;
}
@Override
public void run() {
    //輸出的任務
    while(true){
        s.show();
    }
}

}

//測試類

public class ThreadDemo05 {
    public static void main(String[] args) {
    //創建學生對象
    Student s = new Student();
    //創建線程任務
    Input input = new Input(s);
    Output output = new Output(s);
    //創建線程
    Thread t1 = new Thread(input);
    Thread t2 = new Thread(output);
    //開啓線程      
    t1.start();
    t2.start();
}

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章