如何在多线程中等待客户端

时间:2017-02-25 23:53:30

标签: java multithreading sockets java-threads

我有TCP客户端/服务器。客户端正在运行两个线程C1和C2。服务器运行三个线程S1,S2和S3线程。 C2应在服务器完成S3后收到结果。我在最后一步有问题。客户端和服务器看起来像这样。请建议。

    WITH
    -- input section: a) target table, no dupes
    target(id_comb,attr_pos) AS (
                        SELECT 2,1
    UNION ALL SELECT 2,2
    UNION ALL SELECT 2,3
    UNION ALL SELECT 2,4
    UNION ALL SELECT 3,1
    UNION ALL SELECT 3,2\
UNION ALL SELECT 3,3
UNION ALL SELECT 3,4
UNION ALL SELECT 3,5
UNION ALL SELECT 4,1
UNION ALL SELECT 4,2
UNION ALL SELECT 4,3
)
,
-- input section: b) staging, input, would be a dupe
staging(id_comb,attr_pos) AS (
          SELECT 1,1
UNION ALL SELECT 1,2
UNION ALL SELECT 1,3
UNION ALL SELECT 1,4
)
,
-- query section:
-- add sequence numbers to stage and target
target_s AS (
SELECT 
  ROW_NUMBER() OVER(PARTITION BY id_comb ORDER BY attr_pos) AS seq
, *
FROM target
)
,
staging_s AS (
SELECT 
  ROW_NUMBER() OVER(PARTITION BY id_comb ORDER BY attr_pos) AS seq
, *
FROM staging
)
,
-- horizontally pivot target, NULLS as -1 for later join
target_h AS (
SELECT 
  id_comb
, IFNULL(MAX(CASE seq WHEN 1 THEN attr_pos END),-1) AS attr_pos1
, IFNULL(MAX(CASE seq WHEN 2 THEN attr_pos END),-1) AS attr_pos2
, IFNULL(MAX(CASE seq WHEN 3 THEN attr_pos END),-1) AS attr_pos3
, IFNULL(MAX(CASE seq WHEN 4 THEN attr_pos END),-1) AS attr_pos4
, IFNULL(MAX(CASE seq WHEN 5 THEN attr_pos END),-1) AS attr_pos5
FROM target_s
GROUP BY id_comb ORDER BY id_comb
)
,
-- horizontally pivot staging, NULLS as -1 for later join
staging_h AS (
SELECT 
  id_comb
, IFNULL(MAX(CASE seq WHEN 1 THEN attr_pos END),-1) AS attr_pos1
, IFNULL(MAX(CASE seq WHEN 2 THEN attr_pos END),-1) AS attr_pos2
, IFNULL(MAX(CASE seq WHEN 3 THEN attr_pos END),-1) AS attr_pos3
, IFNULL(MAX(CASE seq WHEN 4 THEN attr_pos END),-1) AS attr_pos4
, IFNULL(MAX(CASE seq WHEN 5 THEN attr_pos END),-1) AS attr_pos5
FROM staging_s
GROUP BY id_comb ORDER BY id_comb
)
SELECT 
  COUNT(*)
FROM target_h
JOIN staging_h USING (
  attr_pos1
, attr_pos2
, attr_pos3
, attr_pos4
, attr_pos5
);

服务器如下所示:

Public class client {
    public static void main (String[] args)
    {
    ClientThread c1= new ClientThread(); // send task to server
    ClientThread c2= new ClientThread(); // result receive
    c1.start();
    c1.join();
    c2.start();
    c2.join();
    }
    }

输出的顺序应如下所示:

Public class server {
    public static void main (String[] args)
    {
    ServerThread s1= new ServerThread(); // receive from client
    ServerThread s2= new serverThread(); // calculate
    ServerThread s3= new serverThread(); // send to client
    s1.start();
    s1.join();
    s2.start();
    s2.join();
    s3.start();
    s3.join();
    }
    }

1 个答案:

答案 0 :(得分:0)

s1.join可能会等待,因此s2可能无法启动或者可能比您想要的更晚启动。首先是所有的开始。

同样适用于客户端,所以首先启动所有启动,然后执行连接。