线程间通信

时间:2015-11-18 04:47:03

标签: java multithreading

我有两个运行t1和t2的线程。当t2通知t1时,t2应立即进入等待状态。但是,这是不可能的,因为一旦它通知t1,它应该完成其当前进程,并且仅在当前线程执行结束之后,t1执行开始。但是我想在t2通知后立即启动t1,以便我可以将t2置于等待状态,以便t1在while循环内通知。同步块可以实现吗?我尝试了以下不起作用的代码。我还评论了编码行,以提及我想要编码的方式。

    public void passNo(int data)//thread t1
        {
            this.data1=data;
            synchronized(thread2)
            {
           System.out.println("thread1 running");
            data1=data1+100;
            try {
                Thread.sleep(1000);
            } catch (Exception e) {
                e.printStackTrace();
            }
             System.out.println("thread1 going to notify thread two");
            thread2.notify();
           /* try {
                thread1.wait();
            } catch (Exception e) {
                e.printStackTrace();
            }*/
            }//sync
            try {
                Thread.sleep(1000);
            } catch (Exception e) {}

               System.out.println("im done, receiver go");
                //}
            }
    public void ramos(int data)//thread t2
        {
            synchronized(thread1)
                {
            try{
            System.out.println("I am thread 2 waiting for thread 1");   
            thread1.wait();//Problem-not notified ever by sender
            System.out.println("Notified by sender thread");}
            catch(InterruptedException ex){}
            System.out.println("I am released");
             n=obj.getInteger();
             setInteger();
             System.out.println("Notified");
            }//sync
            j++;
            //}//while
        }

class ClaObj
{
    public static void main(String[] args) 
    {
        Sender s=new Sender();
        Receiver r=new Receiver();
        r.classobj(s);
        Thread thread1 = new Thread(s);
        Thread thread2 = new Thread(r);
        s.sendthrobj(thread1); 
        r.recvthobj(thread1);
        thread1.start();
        thread2.start();

    }
}

0 个答案:

没有答案