通过Socket实现进程间异步通讯(三)

来源:互联网 发布:类似pid的控制算法 编辑:程序博客网 时间:2024/06/01 03:59

第三步:编写测试代码

 

//Test1.java

package com.hode.thread;

/**
 * @author 泰伯子仪
 *
 * Test1建立一个一般线程,并和Socket信号的服务端邦定
 * 这意味着Test1线程可以通过Socket于其他进程进行通讯
 */
public class Test1 extends CommThread
{

    /**
     * Test1必须继承一般线程CommThread
     * CommThread为虚基类,必须覆写函数dispose()
     */
    public Test1(int sleepTime)
    {
        super(sleepTime);
        this.setName("Test1Thread");
    }
   
    /**
     * 覆写dispose()
     * dispose()为线程中需要处理的事情
     */
    public void dispose()
    {
        for(int i=0 ; i<10 ; i++)
        {
            try
            {
                Thread.sleep(500);
            }
            catch (InterruptedException e){}
            System.out.print(i+" ");
        }
    }
   
    public static void main(String[] args)
    {
        Test1 test1 = new Test1(2000);
        SignalSocketThread ssThread = new SignalSocketThread();
       
        //test1和Socket信号的服务端邦定
        ssThread.serverBind(test1);
       
        //分别启动线程test1和Socket信号的服务端线程
        test1.threadStart();
        ssThread.threadStart();
    }
}

//Test2.java

package com.hode.thread;

/**
 * @author 泰伯子仪
 *
 * Test2是一个希望通过socket与另外一个进程通讯的进程
 * 其中Test2与socket的客户端邦定
 * 而通讯的另一方则是与socket的服务端邦定
 *
 */
public class Test2 implements DealWith
{

    /**
     * Test1必须继承接口DealWith
     * 实现函数dealWith()
     */
    public void dealwith()
    {
        for(int i=0 ; i<10 ; i++)
        {
            try
            {
                Thread.sleep(500);
            }
            catch (InterruptedException e){}
            System.out.print(i+" ");
        }
    }
   
    public static void main(String[] args)
    {
        Test2 test2 = new Test2();
        SignalSocketThread ssThread = new SignalSocketThread();
       
        //与socket的客户端邦定
        ssThread.ClientBind(test2);
    }
}

 

现在分别编译运行Test1和Test2看到什么了

原创粉丝点击