有些人觉得一个个的唤醒线程比较麻烦,这时候使用notifyall是一个不错的选择。从名称上可以看出,它是notify方法的升级,能够对所有的线程进行唤醒,解除线程的阻塞状态。下面我们就notifyall的概念、语法、参数、返回值、使用注意进行分享,然后在实例中唤醒所有线程。
1.概念
对象调用该方法时,队列中所有处于阻塞状态的线程不再阻塞(当然,哪一个线程先运行由系统决定)
2.语法
publicfinalvoidnotifyAll()
3.参数
无
4.返回值
没有返回值
5.使用注意
唤醒的是notify之前wait的线程,对于notify之后的wait线程是没有效果的。
6.实例
classmyThreadimplementsRunnable{
privatebooleanflag;
privateObjectobject;
myThread(booleanflag,Objecto){
this.flag=flag;
this.object=o;
}
privatevoidwaitThread(){
synchronized(object){
System.out.println(Thread.currentThread().getName()+"waitbegin...");
try{
object.wait();
}catch(InterruptedExceptione){
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"waitend...");
}
}
privatevoidnotifyThread(){
synchronized(object){
System.out.println(Thread.currentThread().getName()+"notifybegin...");
object.notify();
System.out.println(Thread.currentThread().getName()+"notifyend...");
}
}
@Override
publicvoidrun(){
if(flag){
waitThread();
}else{
notifyThread();
}
}
}
publicclassTest{
publicstaticvoidmain(String[]args)throwsInterruptedException{
Objectobject=newObject();
myThreadmt2=newmyThread(false,object);
Threadthread1=newThread(mt2,"线程B");
for(inti=0;i<10;i++){
myThreadmt=newmyThread(true,object);
Threadthread=newThread(mt,"线程A"+i);
thread.start();
}
Thread.sleep(1000);
thread1.start();
}
}
原文来自:https://www.py.cn
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END



















































暂无评论内容