08-05 Server、Client可连续发送 生产者、消费者 死锁解决 Server、Client窗口实现

Server、Client可连续发送
< a id=”Server、Client”>

//**MyRead**
public class MyRead implements Runnable{
    private Socket socket;

    public MyRead(Socket socket){
        this.socket=socket;
    }

    @Override
    public void run() {
        BufferedReader br=null;
        try {
            InputStream is=socket.getInputStream();
            br=new BufferedReader(new InputStreamReader(is));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        while(true){
            try {
                String line=br.readLine();
                System.out.println(line);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }           
        }       
    }
}
//**MyWrite**
public class MyWrite implements Runnable{
    private Socket socket;

    public MyWrite(Socket socket){
        this.socket=socket;
    }

    @Override
    public void run() {
        BufferedWriter bw=null;
        try {
            OutputStream os=socket.getOutputStream();
            bw=new BufferedWriter(new OutputStreamWriter(os));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Scanner scanner=new Scanner(System.in);
        while(true){
            String words=scanner.next();
            try {
                bw.write(words+"\n");
                bw.flush();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }   
}
//**MyServer**
public class MyServer {
    public static void main(String[] args) {
        try {
            System.out.println("服务器启动");
            ServerSocket serversocket=new ServerSocket(8080);
            Socket socket=serversocket.accept();
            System.out.println("客户端连接");
            Thread read=new Thread(new MyRead(socket));
            Thread write=new Thread(new MyWrite(socket));
            read.start();
            write.start();
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }   
}
//**MyClient**
public class MyClient {
    public static void main(String[] args) {
        try {

            Socket socket=new Socket("192.168.0.141",8080);         
            Thread read=new Thread(new MyRead(socket));
            Thread write=new Thread(new MyWrite(socket));
            read.start();
            write.start();
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

生产者、消费者

//**Consumer(消费者)**
public class Consumer implements Runnable{
    private Product pro;

    public Consumer(Product pro){
        this.pro=pro;
    }

    @Override
    public void run() {
        while(true){            
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("消费者抢到了仓库");
            synchronized (pro) {
                System.out.println("消费者消费");
                if(pro.getNum()!=0){
                    System.out.println("消费者消费产品");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                pro.setNum(0);
                pro.notify();
            }
        }       
    }
}
//**Producer(生产者)**
public class Producer implements Runnable{
    private Product pro;

    public Producer(Product pro){
        this.pro=pro;
    }

    @Override
    public void run() {
        while(true){
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            synchronized (pro) {
                System.out.println("生产者抢到了仓库");
                if(pro.getNum()==0){
                    System.out.println("生产者生产产品");
                }
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                pro.setNum(1);
                try {
                    pro.wait();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }       
    }
}
//**Product(仓库)** 
public class Product {
    private int num;

    public int getNum() {
        return num;
    }

    public void setNum(int num) {
        this.num = num;
    }
}
//**Test(测试类)**
public class Test {
    public static void main(String[] args) {
        Product product=new Product();
        Thread producer=new Thread(new Producer(product));
        Thread consumer=new Thread(new Consumer(product));
        producer.start();
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        consumer.start();
    }   
}

死锁解决

public class MyRunnable1 implements Runnable{
    String lock1="asd";
    String lock2="qwe";
    @Override
    public void run() {
        synchronized(lock1){
            System.out.println("run1启动");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("run1在等lock2");
            try {
                System.out.println("run1释放lock1");
                lock1.wait();
                System.out.println("run1结束等待得到lock2");
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            synchronized (lock2) {
                System.out.println("run1等到了lock2");
            }
        }               
    }   
}
public class MyRunnable2 implements Runnable{
    String lock1="asd";
    String lock2="qwe";

    @Override
    public void run() {
        synchronized(lock2){
            System.out.println("run2启动");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("run2在等lock1");
            synchronized (lock1) {
                System.out.println("run2等到了lock1");
                System.out.println("唤醒run1");
                lock1.notify();
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                System.out.println("run2运行完锁是lock1的同步块");
            }
        }               
    }
}
public class Test {
    public static void main(String[] args) {
        MyRunnable1 run1=new MyRunnable1();
        MyRunnable2 run2=new MyRunnable2();
        Thread t1=new Thread(run1,"张思");
        Thread t2 =new Thread(run2, "李斯");
        t1.start();
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        t2.start();
    }
}

Server、Client窗口实现

//**MyServer**
public class MyServer extends JFrame {

    private JPanel contentPane;
    private Socket socket;
    private boolean isRunning=true;
    private JTextArea textArea;
    private JList list;
    private DefaultListModel<String> modle;

    public boolean isRunning() {
        return isRunning;
    }

    public void setRunning(boolean isRunning) {
        this.isRunning = isRunning;
    }

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    MyServer frame = new MyServer();
                    frame.setTitle("Server");
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public MyServer() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        JButton btnNewButton = new JButton("启动服务器");
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    ServerSocket server = new ServerSocket(8080);
                    System.out.println("服务器启动");
                    socket = server.accept();
                    Thread t=new Thread(new MyServerRead(MyServer.this));
                    t.start();
                    System.out.println("有客户端接入");
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
        });
        btnNewButton.setBounds(291, 56, 133, 56);
        contentPane.add(btnNewButton);

        textArea = new JTextArea();
        textArea.setBounds(10, 186, 297, 66);
        contentPane.add(textArea);

        JButton btnNewButton_1 = new JButton("发送");
        btnNewButton_1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                write();
            }
        });
        btnNewButton_1.setBounds(318, 203, 106, 32);
        contentPane.add(btnNewButton_1);

        list = new JList();
        list.setBounds(10, 24, 256, 128);
        modle=new DefaultListModel<>();
        list.setModel(modle);
        JScrollPane scroll=new JScrollPane(list);
        scroll.setBounds(10, 24, 256, 128);
        contentPane.add(scroll);

    }
    public void read() {
        try {
            InputStream is = socket.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String line = br.readLine();
            modle.addElement("Client:"+line);
            System.out.println("Client:"+line);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    public void write(){
        try {
            OutputStream os=socket.getOutputStream();
            BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(os));
            String words=textArea.getText();
            System.out.println("服务器发送信息");
            bw.write(words+"\n");
            modle.addElement("Server:"+words);
            textArea.setText("");
            bw.flush();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
//**MyServerRead**
public class MyServerRead implements Runnable {
    private MyServer server;
    public MyServerRead(MyServer server) {
        this.server=server;
    }

    @Override
    public void run() {
        while(server.isRunning()){
            server.read();
        }
    }
}
//**MyClient**
public class MyClient extends JFrame {

    private JPanel contentPane;
    private Socket socket;
    private JTextArea textArea;
    private JList list;
    private DefaultListModel<String> modle;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    MyClient frame = new MyClient();
                    frame.setTitle("Client");
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public MyClient() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        JButton btnNewButton = new JButton("发送");
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                write();
            }
        });
        btnNewButton.setBounds(320, 229, 93, 23);
        contentPane.add(btnNewButton);

        textArea = new JTextArea();
        textArea.setBounds(10, 204, 300, 48);
        contentPane.add(textArea);

        list = new JList();
        list.setBounds(10, 10, 253, 151);
        modle=new DefaultListModel<>();
        list.setModel(modle);
        JScrollPane scroll=new JScrollPane(list);
        scroll.setBounds(10, 24, 256, 128);
        contentPane.add(scroll);

        JButton btnNewButton_1 = new JButton("链接服务器");
        btnNewButton_1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    System.out.println("连接服务器");
                    socket=new Socket("192.168.0.141", 8080);
                    System.out.println("连接服务器成功");
                    Thread t=new Thread(new MyClientRead(MyClient.this));
                    t.start();
                } catch (UnknownHostException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
        });
        btnNewButton_1.setBounds(294, 76, 130, 32);
        contentPane.add(btnNewButton_1);
    }

    public void read() {
        try {
            InputStream is = socket.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String line = br.readLine();
            modle.addElement("Server:"+line);
            System.out.println(line);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void write(){
        try {
            OutputStream os=socket.getOutputStream();
            BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(os));
            String words=   textArea.getText();
            bw.write(words+"\n");
            modle.addElement("Client:"+words);
            textArea.setText("");
            bw.flush();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
//**MyClientRead**
public class MyClientRead implements Runnable{
    private MyClient client;
    public MyClientRead(MyClient  client){
        this.client=client;
    }
    @Override
    public void run() {
        while(true){
            client.read();
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值