java--多线程调度与控制2

来源:互联网 发布:iapp轰炸机源码 编辑:程序博客网 时间:2024/04/28 02:23

★ wait()方法
当前线程进入对象的wait pool。
★notify()/notifyAll()方法
唤醒对象的wait pool中的一个/所有等待线程。
第一种表示:这种有几率性

public class myThread extends Thread{    private static boolean isWait=true;    private int first;    private Object obj;    public myThread(int first,Object obj){        this.obj=obj;        this.first=first;    }    @Override    public void run() {        synchronized (obj) {            for (int i = first; i <= 100; i += 2) {                if(first==1&&i>50&&isWait){                    isWait=false;                    try {                        obj.wait();                    } catch (InterruptedException e) {                        System.out.println("wake up...");                    }                }                System.out.print(i + " ");            }            System.out.println();            if(first==2){                obj.notify();//如果是t1先运行,则不会有错,但是t2先运行,则会出现线程监控异常            }        }    }}
public class client {    public static void main(String[] args) {        Object obj=new Object();        myThread t1=new myThread(1,obj);        myThread t2=new myThread(2,obj);        t1.start();        t2.start();    }}

第二种表示:

public class myRun implements Runnable {    private boolean isWait=true;    @Override    public void run() {        synchronized (this) {            for (int i = 1; i <= 100; i++) {                if (i > 50 && isWait) {                    isWait = false;                    try {                        this.wait();                    } catch (InterruptedException e) {                        System.out.println("wake up...");                    }                }                System.out.print(i + " ");            }            System.out.println();            notify();//只唤醒那些和自己处于同一等待池(被同一对象困住的)的线程之一        }    }}
public class client {    public static void main(String[] args) {        myRun mr=new myRun();        Thread t1=new Thread(mr);        Thread t2=new Thread(mr);        t1.start();        t2.start();    }}

注意:suspend()、resume()和stop()这几个方法现在已经不提倡使用。

0 0