如何使线程在特定时间内等待通知并根据其是否收到通知来执行代码? [英] How to make a thread wait for a notify for a specific time and execute code according to whether it received a notify or not?

查看:96
本文介绍了如何使线程在特定时间内等待通知并根据其是否收到通知来执行代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现一些与UDP有点不同的东西.

I'm trying to implement something which is a bit of a variation of UDP.

服务器线程接收数据报包,对其进行解析,然后将其传递给适当的线程.如果收到消息,它将回复确认,并将其传递给ReceiveMessage线程,该线程在屏幕上打印该消息.

The server thread receives datagram packets, parses them, and passes them to the appropriate thread. If it receives a message, it replies with an acknowledgement and passes it to the ReceiveMessage Thread which prints it onscreen.

我有一个SendMessage线程和ReceiveMessage线程.

I have a SendMessage Thread and a ReceiveMessage thread.

我希望SendMessage线程发送一个数据包,并等待特定超时时间的确认.如果服务器收到确认,我想将notify()发送到SendMessage,如果没有收到确认,我希望SendMessage线程超时并在两种情况下执行不同的代码.我该如何实现?

I want the SendMessage thread to send a packet, and wait for an acknowledgement for a specific timeout period. I want to send a notify() to SendMessage, if the server receives an acknowledgement, and if it doesn't, I want the SendMessage thread to timeout and execute different code in both cases. How can I achieve this?

public class ListenThread extends Thread{

protected DatagramSocket socket = null;
protected Boolean on = true;
protected String id;
protected HashMap <String,Contact> people = null;
protected String user;


public ListenThread(String macadd, String user, HashMap <String, Contact> people) throws SocketException
{
    super("ListenThread");
    this.socket = new DatagramSocket(3333);
    this.id=macadd;
    this.people = people;
    this.user = user;
}

@Override
public void run()
{


    while (on) 
            {

                byte[] buf = new byte[256];
                try{
                        // receive request
                        DatagramPacket packet = new DatagramPacket(buf, buf.length);
                        socket.receive(packet);

                        String packdetails[] = new String(packet.getData(), 0, packet.getLength()).split(":");//Important part of receiving request. Tool used to parse the request
                        InetAddress address = packet.getAddress();

                        if(packdetails[0].equals("D"))  // if it's a Detection Packet                   
                        {/* Handle what to do with Detection packets */
                            }// end of small if
                        }//end of big if
                        else if(packdetails[0].equals("M"))// implies, Message type packet
                        {
                            Timestamp t =new Timestamp(new Date().getTime());
                            //Send Acknowledgement
                            String PString = new String("A:"+id);
                            buf = PString.getBytes();
                            packet = new DatagramPacket(buf, buf.length, address, 3333);

                            new ReceiveMessage(packdetails, address, people, t).start();
                        }
                        else// if it's an acknowledgemnt
                        {
                            //notify the sendmessage thread
                        }
                    }//end of try
                    catch (UnknownHostException e) 
                    {
                        System.err.print("Unable to find IP of current machine");
                    }
                    catch (IOException except)
                    {
                        System.err.print("Network Problem : Unable to send packets!");
                    }
            }//end of while
    }//end of run

}//课程结束

public class SendMessage extends Thread{
protected Contact person = null;
protected String Message = null;

public SendMessage(Contact person, String Message)
{
    this.person=person;
    this.Message= Message;
}
@Override
public void run()
{
    System.out.println(person.getusername()+": "+Message);
    try
    {
        person.SendMessage(Message);
        Thread.currentThread().wait(500);// If i get notify => received acknowledgement
    }
    catch(IOException e)
    {
        System.err.println("Unable to send message!");
    }
    catch (InterruptedException e)
    {
        System.err.print("Woken before receiving notify");
    }
}

推荐答案

有很多方法可以实现这一点,您可以选择CountDownLatch或CyclicBarrier,在此Sender线程将等待接收者对屏障执行操作.另一种选择是让接收方线程将ack消息放入blockingQueue中,而发送方可以在等待队列时使用队列中的ack.

There are many to achieve this, You could opt for CountDownLatch or CyclicBarrier where the Sender thread would wait for the receiver to act on the barrier. Another alternative would be for the receiver thread to put the ack message in a blockingQueue and the sender could consume the ack from the queue while waiting on it.

这篇关于如何使线程在特定时间内等待通知并根据其是否收到通知来执行代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆