11.5作业

1、volatile关键字的作用。
保证了变量的可见性(visibility)。被volatile关键字修饰的变量,如果值发生了变更,其他线程立马可见,避免出现脏读的现象。

2、编写Java程序模拟烧水泡茶最优工序。

class XiShuiHu extends Thread{
	private Integer i;
	XiShuiHu(Integer ii){
		this.i=ii;
	}
	
	public synchronized void run() {
        int ww=0;
		while(++ww<=1) {
			++i;
			int w=0;
			while(++w<=1000) ;
			System.out.println("XiShuiHu--"+i);
		}
	}
}
class ShaoShui implements Runnable{
	private Integer i; 
	public int ww=0;
	ShaoShui(Integer ii){
		this.i=ii;
	}
	
	public void run() {
       
		while(++ww<=15) {
			++i;
			int w=0;
			while(++w<=1000) ;
			System.out.println("ShaoShui--"+i);
		}
	}
}
class Xi implements Runnable{//包含了洗茶壶,洗茶杯,拿茶叶
	private Integer i;      
	public int ww=0;  
	Xi(Integer ii){
		this.i=ii;
	}
	
	public void run() {
   
		while(++ww<=4) {
            ++i;
			int w=0;
			while(++w<=1000) ;
			System.out.println("Xi--"+i);
		}
	}
}
class PaoCha implements Runnable{
	private Integer i;
	PaoCha(Integer ii){
		this.i=ii;
	}

	public void run() {
        int m=0;
		while(++m<=10) {
			++i;
			int w=0;
			while(++w<=1000) ;
			System.out.println("PaoCha--"+i);
		}
	}
}
public class A {
	public static void main(String[] args) {

		Thread xsh =new XiShuiHu(0);
		xsh.start();
		try {
		xsh.join();}
		catch(InterruptedException it){}
		ShaoShui r=new ShaoShui(0);
		Thread sh=new Thread(r);
		Xi r1=new Xi(0);
		Thread x=new Thread(r1);
		sh.start();	
		x.start();
		try {
		sh.join();}
		catch(InterruptedException it){}
		try {
		x.join();}
		catch(InterruptedException it){
		PaoCha r2=new PaoCha(0);
		Thread pc=new Thread(r2);		
		pc.start();
		}
}

3、仿照例15.4,编写完整的基于Socket的多客户/服务器通信程序。

import java.io.*;
import java.net.Socket;

public class TalkClient {

    public static void main(String[] args) {
        Socket socket = null;
        try {
            socket = new Socket("127.0.0.1", 4700);//本机地址
        } catch (IOException e) {
            System.out.println("Can't not listen to " + e);
        }
        //System.out.println("111111");
        try {
            BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            BufferedReader sin = new BufferedReader(new InputStreamReader(System.in));//构建各种输入输出流对象
            BufferedWriter os = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            String readLine;
            while(!(readLine = sin.readLine()).equals("bye")) {
                os.write(readLine + "\n");
                os.flush();
                System.out.println("Server " + ": " + is.readLine());
            }
            os.close();
            is.close();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

服务器 + 线程:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

class ServerThread extends Thread{
    Socket socket = null;
    int clienNum;
    public ServerThread(Socket socket, int num){
        this.socket = socket;
        clienNum = num + 1;
    }
    public void run(){
        try {
            String readLine;
            BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream())); 
            BufferedReader sin = new BufferedReader(new InputStreamReader(System.in));//构建各种输入输出流对象
            BufferedWriter os = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            System.out.println("connected with: " + socket);
            System.out.println("Client " + clienNum + ": " +  is.readLine());
            readLine = sin.readLine();
            while(!readLine.equals("bye")){
                os.write(readLine + "\n"); 
                os.flush();
                System.out.println("Client " + clienNum + ": " +  is.readLine());//添加是哪个客户端发过来的消息
                readLine = sin.readLine();
            }
            os.close();
            is.close();
            socket.close();
        } catch (IOException e) {
            System.out.println("Error: " + e);
        }
    }
}
public class MultiTalkServer {
    private static int clientNum = 0;

    public static void main(String[] args) throws IOException {
        ServerSocket server = null;
        boolean listening = true;
        try {
            server = new ServerSocket(4700);//设置监听端口
        } catch (IOException e) {
            System.out.println("Could not listen on port: 4700");
            System.exit(-1);
        }
        while(listening){
            new ServerThread(server.accept(), clientNum).start();//启动新线程
            clientNum++;
        }
        server.close();
    }
}

4、仿照例15.5,编写完整的基于数据报的多客户/服务器通信程序。

客户端(只能启动一个,这是数据报的规定,但启动多个不会报错):
import java.io.*;
import java.net.*;
public class QuoteClient {
	public static void main(String[] args) throws IOException{
		 DatagramSocket socket=new DatagramSocket();//创建数据报套接字
		 BufferedReader sin = new BufferedReader(new InputStreamReader(System.in));
		 String readLine;
		 InetAddress address=InetAddress.getByName("127.0.0.1");//Server的IP信息
		 while(!(readLine = sin.readLine()).equals("bye")) {
		 byte[] buf = readLine.getBytes();
		 //创建DatagramPacket对象
		 DatagramPacket packet=new DatagramPacket(buf, buf.length, address, 4445);
		 socket.send(packet); //发送
		 buf = new byte[256];
		 //创建新的DatagramPacket对象,用来接收数据报
		 packet=new DatagramPacket(buf,buf.length);
		 socket.receive(packet); //接收
		 buf = packet.getData();
		 //根据接收到的字节数组生成相应的字符串
		 String received=new String(buf);
		 //打印生成的字符串
		 System.out.println("Quote of the Sever: "+received );		 
		}
		 socket.close(); //关闭套接口
	}
}

服务器 + 线程:
import java.io.*;
import java.net.*;

class QuoteServerThread extends Thread//服务器线程
{  
	protected DatagramSocket socket=null;//记录和本对象相关联的DatagramSocket对象
	protected BufferedReader in=null;//用来读文件的一个Reader
	protected boolean moreQuotes=true;//标志变量,是否继续操作
	public QuoteServerThread() throws IOException {//无参数的构造函数
    this("QuoteServerThread");//以QuoteServerThread为默认值调用带参数的构造函数

	}
	public QuoteServerThread(String name) throws IOException {
		super(name); //调用父类的构造函数
		socket=new DatagramSocket(4445);//在端口4445创建数据报套接字		
		in= new BufferedReader(new InputStreamReader(System.in));
	}	
	 public void run() //线程主体
	 {
		while(moreQuotes) {
			try{
				byte[] buf=new byte[256]; //创建缓冲区
				DatagramPacket packet=new DatagramPacket(buf,buf.length);
				//由缓冲区构造DatagramPacket对象
				socket.receive(packet); //接收数据报				
				//打印出客户端发送的内容
				System.out.println("Client : "+new String(packet.getData())); 
				//从屏幕获取输入内容,作为发送给客户端的内容
				String dString= in.readLine();    
				//如果是bye,则向客户端发完消息后退出
				if(dString.equals("bye")){moreQuotes=false;}
				buf=dString.getBytes();//把String转换成字节数组,以便传送
				//从Client端传来的Packet中得到Client地址
				InetAddress address=packet.getAddress();
				int port=packet.getPort(); //端口号
				//根据客户端信息构建DatagramPacket
				packet=new DatagramPacket(buf,buf.length,address,port);
				socket.send(packet); //发送数据报
			}catch(IOException e) { //异常处理
			    e.printStackTrace(); //打印错误栈
				moreQuotes=false; //标志变量置false,以结束循环
			}
		 }
		 socket.close(); //关闭数据报套接字
	   }	
}

public class QuoteServer{
	public static void main(String args[]) throws java.io.IOException
	{
		new QuoteServerThread().start();//启动一个QuoteServerThread线程
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值