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

本文介绍了Java中线程同步的基本概念,包括wait()、notify()和notifyAll()方法的使用方式及注意事项。通过两个示例代码展示了如何在具体场景中应用这些方法来实现线程间的同步。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

★ 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()这几个方法现在已经不提倡使用。

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值