观察者模式实现简单聊天

这里写图片描述

锁的处理

notify() 唤醒在此对象监视器上等待的单个线程。如果所有线程都在此对象上等待,则会选择唤醒其中一个线程。选择是任意性的,并在对实现做出决定时发生。线程通过调用其中一个 wait 方法,在对象的监视器上等待。
直到当前线程放弃此对象上的锁定,才能继续执行被唤醒的线程。被唤醒的线程将以常规方式与在该对象上主动同步的其他所有线程进行竞争;例如,唤醒的线程在作为锁定此对象的下一个线程方面没有可靠的特权或劣势。

wait() 在其他线程调用此对象的 notify() 方法或 notifyAll() 方法前,导致当前线程等待。换句话说,此方法的行为就好像它仅执行 wait(0) 调用一样。
当前线程必须拥有此对象监视器。该线程发布对此监视器的所有权并等待,直到其他线程通过调用 notify 方法,或 notifyAll 方法通知在此对象的监视器上等待的线程醒来。然后该线程将等到重新获得对监视器的所有权后才能继续执行。

package com.thread1.android;

public class MyRunnable2 implements Runnable {
    private String lock1 = "1230";
    private String lock2 = "1224";

    @Override
    public void run() {
        synchronized (lock2) {
            System.out.println("lock2启动");
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {

                e.printStackTrace();
            }

            System.out.println("我在等待lock1");
            synchronized (lock1) {
                System.out.println("等到了lock1");
                System.out.println("唤醒等待的lock1");
                lock1.notify();
                //notify() 唤醒在此对象监视器上等待的单个线程
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                System.out.println("run2运行完,所是lock1的同步");
            }
        }

    }

}
*******************************************************
package com.thread1.android;

public class MyRunnable1 implements Runnable {
    private String lock1 = "1230";
    private String lock2 = "1224";

    @Override
    public void run() {
        synchronized (lock1) {
            System.out.println("run1启动");
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {

                e.printStackTrace();
            }

            System.out.println("我在等待lock2");
            try {System.out.println("run1结束等待并");
                lock1.wait();
                //wait()  在其他线程调用此对象的 notify() 方法或 notifyAll() 
                //方法前,导致当前线程等待。

            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
        synchronized (lock2) {
            System.out.println("等到lock2");
        }

    }

}
******************************************************
package com.thread1.android;

public class Test {

    public static void main(String[] args) {
        MyRunnable1 r1=new MyRunnable1();
        MyRunnable2 r2=new MyRunnable2();

        Thread t1=new Thread(r1,"张丹");
        Thread t2=new Thread(r2,"李四");

        t1.start();
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        t2.start();

    }

}

观察者模式

多线程实现聊天

package com.lingzhuo.test;

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.border.EmptyBorder;
import javax.swing.plaf.basic.DefaultMenuLayout;

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.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

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

        textArea = new JTextArea();
        textArea.setBounds(49, 436, 500, 101);
        contentPane.add(textArea);

        JButton btnNewButton = new JButton("发送");
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                write();
            }
        });
        btnNewButton.setBounds(589, 436, 129, 101);
        contentPane.add(btnNewButton);

        list = new JList();
        list.setBounds(61, 10, 484, 416);
        modle=new DefaultListModel<>();
        list.setModel(modle);
        contentPane.add(list);

        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.30", 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(615, 68, 103, 86);
        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("服务器说的"+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(words);
            textArea.setText("");
            bw.flush();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
***************************************************
package com.lingzhuo.test;

public class MyClientRead implements Runnable{
    private MyClient client;
    public MyClientRead(MyClient  client){
        this.client=client;
    }
    @Override
    public void run() {
        while(true){
            client.read();
        }
    }

}
*************************************************************
package com.lingzhuo.test;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.awt.event.ActionEvent;
import javax.swing.JTextArea;

public class MyServer extends JFrame {

    private JPanel contentPane;
    private Socket socket;
    private boolean isRunning=true;
    private JTextArea textArea;
    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.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

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

        JButton button = new JButton("\u542F\u52A8\u670D\u52A1");
        button.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();
                }
            }
        });
        button.setBounds(22, 10, 475, 87);
        contentPane.add(button);

        textArea = new JTextArea();
        textArea.setBounds(100, 476, 518, 138);
        contentPane.add(textArea);

        JButton button_1 = new JButton("\u53D1\u7ED9\u5BA2\u6237\u7AEF");
        button_1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                write();
            }
        });
        button_1.setBounds(671, 531, 93, 23);
        contentPane.add(button_1);
    }

    public void read() {
        try {
            InputStream is = socket.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String line = br.readLine();
            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();
            System.out.println("服务器发送信息");
            bw.write(words+"\n");
            textArea.setText("");
            bw.flush();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
**********************************************************
package com.lingzhuo.test;

public class MyServerRead implements Runnable {
    private MyServer server;
    public MyServerRead(MyServer server) {
        this.server=server;
    }
    @Override
    public void run() {
        while(server.isRunning()){
            server.read();
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值