Java多线程时间切换

时间:2013-07-02 21:38:09

标签: java multithreading

我对Java中多线程如何工作的了解很少。我知道当你运行两个线程时,Java会为每个线程分配“时间块”以供执行
例如:

public void test()
{
    Thread testThread = new Thread(new TestThread());
    testThread.start();

    for (int i = 0; i < Integer.MAX_VALUE; ++i)
        System.out.print("a");
}

private class TestThread extends Thread
{
    public void run()
    {
        for (int i = 0; i < Integer.MAX_VALUE; ++i)
            System.out.print("b");
    }
}

会打印出类似的内容:
aaaaaaaaaaabbbbbbbbbbbbaaaaaaaaaaabbbbbbbbbbbbbaaaaaa ...
而不是:
abababababababababababababababab .....


我的问题是:是否可以减少“时间块”,以便我们更接近: aabbaaabbaabbaaabbaabbbaabbaabbbaabbaaa ...


为什么?我正在尝试编写一个苹果推送通知服务器(只是为了好玩)。当您向Apple推送通知服务写入请求时,可能会发生一两件事: 1.如果请求有效,则不会返回任何内容 2.如果请求无效,它将返回错误代码并关闭连接,并且在无效请求之后和连接关闭之前发送的任何请求都将被丢弃。

因为读取套接字会阻塞,直到数据可供读取(如果我不写任何无效请求,这可能永远不会发生),我不能简单地在每次写入后读取,看看是否有错误而没有设置200-500毫秒的超时。如果我们有一百万个写入请求(非常可能),这个超时会增加55 - 138 HOURS,并且由于短暂的超时会导致请求永远不会被发送,我们可能会错过返回的错误。

所以我有两个线程,比如上面的例子,一个写入服务器,一个正在读取,等待查看是否返回错误。问题在于:如果请求#4不好但我们在读取错误并且连接关闭之前编写#5-#10,则苹果服务会丢弃请求#5-10。因此,一旦我们知道#4是坏的并且我们知道我们写的最后一个请求是#10,我们需要重新排队#5-10再次发送。

我现在遇到的问题是由于大量的“时间卡盘”,我能够在读取线程读取之前写入#1-#400请求#5出现错误,因此#6-#400被重新排队并发送再次。然后读取线程读取#21的错误,因此#22-#400被重新排队并再次发送...等。理想情况下,读取线程将能够从写入的每5-10个请求中读取套接字。

来源:

private Object readWriteLock = new Object();
private volatile int     lastWrittenIndex;
private volatile boolean doneWriting;
private List<PushNotificationRequest> pushNotificationRequestsResnedList = new ArrayList<PushNotificationRequest>();

public boolean write()
{
    // get the requests read list
    List<PushNotificationRequest> requests = getPushNotificationRequests(false);

    // as long as there are more notifications to write...
    while (requests.size() > 0)
    {
        lastWrittenIndex = -1;
        doneWriting = false;

        // create and start the read thread
        Thread readThread = new Thread(new ReadThread(), "APNS Reader");
        readThread.start();

        for (int i = 0; i < requests.size(); ++i)
        {
            PushNotificationRequest request = requests.get(i);

            // write
            boolean success = false;

            // attempt to send the notification a number of times
            for (int j = 0; j < MAX_NUM_PN_WRITE_ATTEMPTS; ++j)
            {
                synchronized (readWriteLock)
                {
                    try
                    {
                        // get the socket connection
                        SSLSocket socket = getAppleServiceSSLSockett();
                        OutputStream socketOutputStream = socket.getOutputStream();

                        socketOutputStream.write(request.binary);
                        socketOutputStream.flush();

                        success = true;
                        lastWrittenIndex = i;

                        break;
                    }
                    catch (IOException e)
                    {
                        e.printStackTrace();
                    }
                    catch (AppleServiceConnectionException e)
                    {
                        e.printStackTrace();
                    }
                }
            }

            if (!success)
                System.err.println("APNS Unable to send push notification:\n" + request);
        }

        // wait for some time so we can make sure the read thread can read everything
        try
        {
            Thread.sleep(Config.APNS_READ_TIME_AFTER_DONE_WRITING_MILLISECONDS);
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }

        // let the read thread know we are done writing and close the connection so it unblocks
        doneWriting = true;
        closeAppleServiceSSLSockett();

        // wait for the read thread to return
        try
        {
            readThread.join();
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }


        // clear the reading list
        requests.clear();

        // add the requests from the re-send to the list
        if (pushNotificationRequestsResnedList.size() > 0)
        {
            requests.addAll(pushNotificationRequestsResnedList);

            // clear the re-send list
            pushNotificationRequestsResnedList.clear();
        }
    }
}

private class ReadThread extends Thread
{
    public void run()
    {
        byte[] readBuffer = new byte[1024];
        int numBytesRead;
        int totalNumBytesRead;

        while (!doneWriting)
        {
            try
            {
                // get the socket connection
                SSLSocket socket = getAppleServiceSSLSockett();
                socket.setSoTimeout(Config.APNS_READ_TIMEOUT_MILLISECONDS);

                InputStream socketInputStream = socket.getInputStream();

                // read (blocking)
                totalNumBytesRead = 0;
                while ((numBytesRead = socketInputStream.read(readBuffer)) != -1)
                    totalNumBytesRead += numBytesRead;

                // check for an error
                if (totalNumBytesRead > 0)
                {
                    synchronized (readWriteLock)
                    {
                        try
                        {
                            PushNotificationResponse response = new PushNotificationResponse(readBuffer, 0);
                            System.err.println("APNS Read got response with id: " + response.identifier);

                            // find the request with the given identifier
                            int i;
                            for (i = lastWrittenIndex; i > -1; --i)
                            {
                                if (pushNotificationRequestsReadingList.get(i).identifier == response.identifier)
                                    break;
                            }


                            if (i == -1)
                            {
                                // something went wrong, we didn't find the identifier
                                System.err.println("APNS Read unable to find request with id: " + response.identifier);
                            }
                            else
                            {
                                System.err.println("APNS Read " + response.getErrorMessage(pushNotificationRequestsReadingList.get(i)));

                                // add the requests between the bad request and the last written (included)
                                for (++i; i <= lastWrittenIndex; ++i)
                                    pushNotificationRequestsResnedList.add(pushNotificationRequestsReadingList.get(i));
                            }
                        }
                        catch (InvalidPushNotificationResponseException g)
                        {
                            g.printStackTrace();
                        }
                    }

                    // the socket will be closed, reopen it
                    try
                    {
                        reopenAppleServiceSSLSockett();
                    }
                    catch (AppleServiceConnectionException e)
                    {
                        e.printStackTrace();
                    }
                }
            }
            catch (SocketException e)
            {
                // ignore a close, it is expected
                if (!e.getMessage().equals("Socket closed"))
                    e.printStackTrace();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            catch (AppleServiceConnectionException e)
            {
                e.printStackTrace();
            }
        }
    }
}

2 个答案:

答案 0 :(得分:1)

您是否尝试过使用Thread.yield()来请求线程调度程序移动到下一个线程?

// using Thread.yield() MIGHT give you the results you want
for (int i = 0; i < Integer.MAX_VALUE; ++i)
{
    System.out.print("a");
    Thread.yield();
}

请记住,线程调度取决于底层操作系统,因此以上只是一个有根据的猜测 - 我还没有尝试过运行它。有关示例,请参阅here

编辑:here是关于不同平台如何实现收益的更多信息。

答案 1 :(得分:1)

这不是java,但实际上操作系统会调度线程的时间块。在生产者/消费者场景中,您希望在生产者方面提供公平性,以便一个生产者在所有其他生产者给出自己的产出后给出一个输出。为此,您可以使用一个线程来绕过几个懒惰的生成器。那就是:

N个生产者在生产者上公开getNextThing()和1个消费者循环,并将结果传递给您消费的列表