首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >请帮助我解决代码中的非法监控状态异常

请帮助我解决代码中的非法监控状态异常
EN

Stack Overflow用户
提问于 2014-12-08 15:33:46
回答 1查看 58关注 0票数 0
代码语言:javascript
运行
复制
//The below code is throwing illegalmonitorstate exception.
public class Multithreading implements Runnable {

    static int i=0;
    public boolean ist1=true;
    public boolean ist2=false;

    public static void main (String args[]){
        Multithreading ins= new Multithreading();
        Thread t1 =new Thread(ins);
        Thread t2 =new Thread(ins);
        t1.setName("Even");
        t2.setName("ODD");

        t1.start();
        t2.start();
    }  

    @Override
    // Wanted to right run method used by two threads to print
    // even and odd number in sequence 

    public void run() {

        while(i<=9){

            try{
                if(Thread.currentThread().getName().contains("Even")&& i%2==0){
                    System.out.println(Thread.currentThread().getName()+"________"+i);
                    i=i+1;
                    Thread.currentThread().wait(100);
                }
                // due to wait is not used with synchronized but
                // i am not able to correct it  

                if(Thread.currentThread().getName().contains("ODD") && i%2>=1){
                    System.out.println(Thread.currentThread().getName()+"________"+i);
                    i=i+1;
                    Thread.currentThread().wait(100);

                    //System.out.println(e);    
                }
            }catch(Exception e){
                System.out.println(e);  
            }
        }
    }
}
EN

回答 1

Stack Overflow用户

发布于 2014-12-08 16:06:01

要暂停线程,需要在本例中使用Thread.sleep()而不是wait()

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27353364

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档