线程的复习
生产者和消费者
public class Consumer implements Runnable{
private Product pro;
public Consumer(Product pro){
this.pro = pro;
}
@Override
public void run() {
while(true){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized (pro) {
System.out.println("消费者抢到仓库");
if(pro.getNum()==1){
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("消费者消费一件产品");
pro.setNum(0);
System.out.println("消费者唤醒生产者");
pro.notify();
}
}
}
}
}
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){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("生产者生产一件产品");
pro.setNum(1);
System.out.println("生产者休眠");
try {
pro.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
public class Product {
private int num = 0;
public Product(){
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
}
public class Test {
public static void main(String[] args) {
Product pro = new Product();
Producer producer = new Producer(pro);
Consumer consumer = new Consumer(pro);
Thread t1 = new Thread(producer);
Thread t2 = new Thread(consumer);
t1.start();
t2.start();
}
}
运行结果:
生产者消费者2
和上例不同的是将锁整合到方法中去了
public class Consumer implements Runnable{
private Product pro;
public Consumer(Product pro){
this.pro = pro;
}
@Override
public void run() {
while(true){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pro.cost();
}
}
}
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();
}
pro.produce();
}
}
}
public class Product {
public synchronized void produce() {
System.out.println("生产者抢到仓库");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("生产者生产一件产品");
System.out.println("生产者休眠");
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public synchronized void cost() {
System.out.println("消费者抢到仓库");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("消费者消费一件产品");
System.out.println("消费者唤醒生产者");
notify();
}
}
public class Test {
public static void main(String[] args) {
Product pro = new Product();
Producer producer = new Producer(pro);
Consumer consumer = new Consumer(pro);
Thread t1 = new Thread(producer);
Thread t2 = new Thread(consumer);
t1.start();
t2.start();
}
}
运行结果:
服务器和客户端在多线程下互相通信
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;
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));
while(true){
String s= br.readLine();
System.out.println(s);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.Scanner;
public class MyWrite implements Runnable{
private Socket socket;
public MyWrite(Socket socket){
this.socket = socket;
}
public void run() {
BufferedWriter bw = null;
try {
OutputStream out = socket.getOutputStream();
bw = new BufferedWriter(new OutputStreamWriter(out));
Scanner scanner = new Scanner(System.in);
while(true){
String str = scanner.next();
bw.write(str+"\n");
bw.flush();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
import java.io.IOException;
import java.net.Socket;
public class Client {
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 8080);
System.out.println("连入服务器");
Thread t1 = new Thread(new MyRead(socket));
Thread t2 = new Thread(new MyWrite(socket));
t1.start();
t2.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) {
try {
ServerSocket server = new ServerSocket(8080);
Socket socket = server.accept();
System.out.println("服务器启动");
System.out.println("有客户端连入");
Thread t1 = new Thread(new MyRead(socket));
Thread t2 = new Thread(new MyWrite(socket));
t1.start();
t2.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
运行结果:
服务器和客户端在UDP多线程下互相通信
import java.net.DatagramSocket;
import java.net.SocketException;
public class Getter {
public static void main(String[] args) {
try {
DatagramSocket get = new DatagramSocket(8080);
DatagramSocket give = new DatagramSocket();
Thread t1 = new Thread(new Give(give,8088));
Thread t2 = new Thread(new Get(get));
t2.start();
t1.start();
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
import java.net.DatagramSocket;
import java.net.SocketException;
public class Sender {
public static void main(String[] args) {
try {
DatagramSocket get = new DatagramSocket(8088);
DatagramSocket give = new DatagramSocket();
Thread t1 = new Thread(new Give(give,8080));
Thread t2 = new Thread(new Get(get));
t1.start();
t2.start();
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.Scanner;
public class Get implements Runnable{
DatagramSocket get;
public Get(DatagramSocket get){
this.get = get;
}
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
byte [] arr = new byte[1024];
DatagramPacket packetreceive = new DatagramPacket(arr, arr.length);
try {
get.receive(packetreceive);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] data = packetreceive.getData();
System.out.println("Sender收到:"+new String(data,0,data.length));
}
}
}
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Scanner;
public class Give implements Runnable{
Scanner scanner = new Scanner(System.in);
DatagramSocket give;
int port;
public Give(DatagramSocket give,int port){
this.give = give;
this.port = port;
}
@Override
public void run() {
while(true){
try {
String s = scanner.next();
byte [] array = s.getBytes();
DatagramPacket sender = new DatagramPacket(array, array.length,InetAddress.getByName("LocalHost"), port);
System.out.println("发送:"+s);
give.send(sender);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
运行结果:
JFrame窗口
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server implements Runnable{
private ServerFrame sf;
public Server(ServerFrame sf){
this.sf = sf;
}
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
sf.read();
}
}
}
import java.io.IOException;
import java.net.Socket;
public class Client implements Runnable{
private ClientFrame cf;
public Client(ClientFrame cf){
this.cf = cf;
}
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
cf.read();
}
}
}
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Image;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.DefaultListModel;
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.SpringLayout;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import javax.swing.JList;
public class ServerFrame extends JFrame {
private BufferedReader br = null;
private JPanel contentPane;
private JTextField textField;
private Socket socket;
private JList list;
private DefaultListModel<String> model;
private BufferedWriter bw;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ServerFrame frame = new ServerFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public ServerFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("服务器");
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
JButton btnNewButton = new JButton("服务开启");
btnNewButton.setBounds(10, 229, 88, 23);
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 Server(ServerFrame.this));
t.start();
System.out.println("有客户端连入");
} catch (IOException ex) {
// TODO Auto-generated catch block
ex.printStackTrace();
}
}
});
contentPane.setLayout(null);
contentPane.add(btnNewButton);
JButton btnNewButton_1 = new JButton("发送");
btnNewButton_1.setBounds(99, 229, 88, 23);
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
write();
}
});
contentPane.add(btnNewButton_1);
textField = new JTextField();
textField.setBounds(193, 230, 230, 22);
contentPane.add(textField);
textField.setColumns(10);
list = new JList();
list.setBounds(10, 10, 414, 209);
model = new DefaultListModel<>();
list.setModel(model);
contentPane.add(list);
}
public void read(){
InputStream in;
try {
in = socket.getInputStream();
br = new BufferedReader(new InputStreamReader(in));
String line = br.readLine();
model.addElement("客户端:"+line);
System.out.println(line);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void write(){
try {
OutputStream out = socket.getOutputStream();
bw = new BufferedWriter(new OutputStreamWriter(out));
String line = textField.getText();
bw.write(line+"\n");
model.addElement("服务器:"+line);
textField.setText("");
bw.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.JTextArea;
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 java.awt.event.ActionEvent;
public class ClientFrame extends JFrame {
private BufferedReader br = null;
private JPanel contentPane;
private JTextField textField;
private Socket socket;
private JList list;
private DefaultListModel<String> model;
private BufferedWriter bw;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ClientFrame frame = new ClientFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public ClientFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("客户端");
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 {
socket = new Socket("localhost", 8080);
System.out.println("连接到服务器");
Thread t = new Thread(new Client(ClientFrame.this));
t.start();
} catch (UnknownHostException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
btnNewButton.setBounds(10, 229, 103, 23);
contentPane.add(btnNewButton);
JButton btnNewButton_1 = new JButton("发送");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
write();
}
});
btnNewButton_1.setBounds(113, 229, 93, 23);
contentPane.add(btnNewButton_1);
textField = new JTextField();
textField.setBounds(216, 230, 208, 21);
contentPane.add(textField);
textField.setColumns(10);
list = new JList();
list.setBounds(10, 10, 414, 209);
model = new DefaultListModel<>();
list.setModel(model);
contentPane.add(list);
}
public void read(){
InputStream in;
try {
in = socket.getInputStream();
br = new BufferedReader(new InputStreamReader(in));
String line = br.readLine();
model.addElement("服务器:"+line);
System.out.println(line);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void write(){
try {
OutputStream out = socket.getOutputStream();
bw = new BufferedWriter(new OutputStreamWriter(out));
String line = textField.getText();
bw.write(line+"\n");
model.addElement("客户端:"+line);
textField.setText("");
bw.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
运行结果: