Java第七次实验作业

1、用两个线程玩猜数字游戏,第一个线程负责随机给出1到100之间的一个整数,第二个线程负责猜出这个数。要求每当第二个线程给出自己的猜测后,第一个线程都会提示“猜小了”、“猜大了”或“猜对了”。猜数之前,要求第二个线程要等待第一个线程设置好要猜测的数。第一个线程设置好猜测数之后,两个线程还要互相等待,其原则是,第二个线程给出自己的猜测后,等待第一个线程给出的提示;第一个线程给出提示后,等待给第二个线程给出猜测,如此进行,直到第二个线程给出正确的猜测后,两个线程进入死亡状态。

代码:

package Text;//包名

public class Number implements Runnable {

    final int SMALLER=-1,LARGER=1,SUCCESS=8;

    int realNumber,guessNumber,min=0,max=100,message=SMALLER;

    boolean pleaseGuess=false,isGiveNumber=false;

    Thread giveNumberThread,guessNumberThread;

    Number() {

     giveNumberThread=new Thread(this);

     guessNumberThread=new Thread(this);

    }

    public void run() {

        for(int count=1;true;count++) {

            setMessage(count);

            if( message==SUCCESS)

                return;

        }

    }

    public synchronized void setMessage(int count) {

        if(Thread.currentThread()==giveNumberThread&&isGiveNumber==false) {

            realNumber=(int)(Math.random()*100)+1;

            System.out.println("随机给你一个1至100之间的数,猜猜是多少?");

            isGiveNumber=true;

            pleaseGuess=true;

        }

        if(Thread.currentThread()==giveNumberThread) {

            while(pleaseGuess==true)

                try  { wait();  //让出CPU使用权,让另一个线程开始猜数

                }

                catch(InterruptedException e){}

            if(realNumber>guessNumber)  { //结束等待后,根据另一个线程的猜测给出提示

                message=SMALLER;

                System.out.println("你猜小了");

            }

            else if(realNumber<guessNumber) {

                message=LARGER;

                System.out.println("你猜大了");

            }

            else {

                message=SUCCESS;

                System.out.println("恭喜,你猜对了");

            }

            pleaseGuess=true;

        }

        if(Thread.currentThread()==guessNumberThread&&isGiveNumber==true) {

            while(pleaseGuess==false)

                try { wait();  //让出CPU使用权,让另一个线程给出提示

                }

                catch(InterruptedException e){}

            if(message==SMALLER) {

                min=guessNumber;

                guessNumber=(min+max)/2;

                System.out.println("我第"+count+"次猜这个数是:"+guessNumber);

            }

            else if(message==LARGER) {

                max=guessNumber;

                guessNumber=(min+max)/2;

                System.out.println("我第"+count+"次猜这个数是:"+guessNumber);

            }

            pleaseGuess=false;

        }

        notifyAll();

    }

}

package Text;

 

public class TwoThreadGuessNumber {

    public static void main(String args[]) {

        Number number=new Number();

        number.giveNumberThread.start();

        number.guessNumberThread.start();

    }

}

2、创建一个URL对象,然后让URL对象返回输入流,通过该输入流读取URL所包含的资源文件

请按模板要求,将【代码】替换为Java程序代码。

代码:

package Text;

 

import java.awt.*;

import java.awt.event.*;

import java.net.*;

import java.io.*;

import javax.swing.*;

class NetWin extends JFrame implements ActionListener,Runnable {

    JButton button;

    URL url;

    JTextField inputURLText; //输入URL

    JTextArea area;

    byte b[]=new byte[118];

    Thread thread;

    NetWin() {

        inputURLText=new JTextField(20);

        area=new JTextArea(12,12);

        button=new JButton("确定");

        button.addActionListener(this);

        thread=new Thread(this);

        JPanel p=new JPanel();

        p.add(new JLabel("输入网址:"));

        p.add(inputURLText);

        p.add(button);

        add(area,BorderLayout.CENTER);

        add(p,BorderLayout.NORTH);

        setBounds(60,60,560,300);

        setVisible(true);

        validate();

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }

    public void actionPerformed(ActionEvent e) {

        if(!(thread.isAlive()))

            thread=new Thread(this);

        try{  thread.start();

        }

        catch(Exception ee) {

            inputURLText.setText("我正在读取"+url);

        }

    }

    public void run() {

        try { int n=-1;

            area.setText(null);

            String name=inputURLText.getText().trim();

            //使用字符串name创建url对象

            url=new URL(name);

            String hostName =url.getHost(); //url调用getHost()

            int urlPortNumber= url.getPort();

            String fileName=url.getFile();

            InputStream in = url.openStream(); //url调用方法返回一个输入流

            area.append("\n主机:"+hostName+"端口:"+urlPortNumber+

                    "包含的文件名字:"+fileName);

            area.append("\n文件的内容如下:");

            while((n=in.read(b))!=-1) {

                String s=new String(b,0,n);

                area.append(s);

            }

        }

        catch(MalformedURLException e1) {

            inputURLText.setText(""+e1);

            return;

        }

        catch(IOException e1) {

            inputURLText.setText(""+e1);

            return;

        }

    }

}

package Text;

 

public class ReadURLSource {

    public static void main(String args[]) {

        new NetWin();

    }

}

3、客户端和服务器建立套接字连接后,客户将如下格式的账单发送给服务器:

"房租:2189元 水费:112.9元 电费:569元 物业费:832元"

服务器返回给客户的信息是:

您的账单:

"房租:2189元 水费:112.9元 电费:569元 物业费:832元

总计:3699.9元

请按模板要求,将【代码】替换为Java程序代码。

代码:

package Text4;

import java.io.*;

import java.net.*;

import java.util.*;

public class ClientItem  {

    public static void main(String args[]) {

        Scanner scanner = new Scanner(System.in);

        Socket clientSocket=null;

        DataInputStream inData=null;

        DataOutputStream outData=null;

        Thread thread ;

        Read read=null;

        try{  clientSocket=new Socket();

            read = new Read();

            thread = new Thread(read);   //负责读取信息的线程

            System.out.print("输入服务器的IP:");

            String IP = scanner.nextLine();

            System.out.print("输入端口号:");

            int port = scanner.nextInt();

            String enter=scanner.nextLine(); //消耗回车

            if(clientSocket.isConnected()){}

            else{

                InetAddress  address=InetAddress.getByName(IP);

                InetSocketAddress socketAddress=new InetSocketAddress(address,port);

                clientSocket.connect(socketAddress);

                InputStream in=clientSocket.getInputStream();//clientSocket调用getInputStream()返回输入流

                OutputStream out=clientSocket.getOutputStream();//clientSocket调用getOutputStream()返回输出流

                inData =new DataInputStream(in);

                outData = new DataOutputStream(out);

                read.setDataInputStream(inData);

                read.setDataOutputStream(outData);

                thread.start();  //启动负责读信息的线程

            }

        }

        catch(Exception e) {

            System.out.println("服务器已断开"+e);

        }

    }

}

class Read implements Runnable {

    Scanner scanner = new Scanner(System.in);

    DataInputStream in;

    DataOutputStream out;

    public void setDataInputStream(DataInputStream in) {

        this.in = in;

    }

    public void setDataOutputStream(DataOutputStream out) {

        this.out = out;

    }

    public void run() {

        System.out.println("输入账单:");

        String content = scanner.nextLine();

        try{  out.writeUTF("账单"+content);

            String str = in.readUTF();

            System.out.println(str);

            str = in.readUTF();

            System.out.println(str);

            str = in.readUTF();

            System.out.println(str);

        }

        catch(Exception e) {}

    }

}

package Text4;

 

import java.io.*;

import java.net.*;

import java.util.*;

public class ServerItem {

    public static void main(String args[]) {

        ServerSocket server=null;

        ServerThread thread;

        Socket you=null;

        while(true) {

            try{  server= new ServerSocket(4331);//创建在端口4331上负责监听的 ServerSocket对象

            }

            catch(IOException e1) {

                System.out.println("正在监听");

            }

            try{  System.out.println("正在等待客户");

                you= server.accept();// server调用accept()返回和客户端相连接的Socket对象

                System.out.println("客户的地址:"+you.getInetAddress());

            }

            catch (IOException e) {

                System.out.println(""+e);

            }

            if(you!=null) {

                new ServerThread(you).start();

            }

        }

    }

}

class ServerThread extends Thread {

    Socket socket;

    DataInputStream in=null;

    DataOutputStream out=null;

    ServerThread(Socket t) {

        socket=t;

        try  { out=new DataOutputStream(socket.getOutputStream());

            in=new DataInputStream(socket.getInputStream());

        }

        catch (IOException e) {}

    }

    public void run() {

        try{

            String item = in.readUTF();

            Scanner scanner = new Scanner(item);

            scanner.useDelimiter("[^0123456789.]+");

            if(item.startsWith("账单")) {

                double sum=0;

                while(scanner.hasNext()){

                    try{  double price = scanner.nextDouble();

                        sum = sum+price;

                        System.out.println(price);

                    }

                    catch(InputMismatchException exp){

                        String t = scanner.next();

                    }

                }

                out.writeUTF("您的账单:");

                out.writeUTF(item);

                out.writeUTF("总额:"+sum+"元");

            }

        }

        catch(Exception exp){}

    }

}

4、编写基于多线程的服务器和客户端进行通信的程序,要求:

1)客户端从键盘输入整数n,发送给服务器;

2)服务器计算s=1!+2!+……+n!,并将s的值返回客户端;

3)客户端收到后,在显示器上输出结果。

要求,可以一人单独完成,也可以两人一组合作完成。

代码:

客户端:

package Text4;

import java.io.*;

import java.net.*;

import java.util.*;

public class ClientItem  {

    public static void main(String args[]) {

        Scanner scanner = new Scanner(System.in);

        Socket clientSocket=null;

        DataInputStream inData=null;

        DataOutputStream outData=null;

        Thread thread ;

        Read read=null;

        try{  clientSocket=new Socket();

            read = new Read();

            thread = new Thread(read);   //负责读取信息的线程

            System.out.print("输入服务器的IP:");

            String IP = scanner.nextLine();

            System.out.print("输入端口号:");

            int port = scanner.nextInt();

            String enter=scanner.nextLine(); //消耗回车

            if(clientSocket.isConnected()){}

            else{

                InetAddress  address=InetAddress.getByName(IP);

                InetSocketAddress socketAddress=new InetSocketAddress(address,port);

                clientSocket.connect(socketAddress);

                InputStream in=clientSocket.getInputStream();//clientSocket调用getInputStream()返回输入流

                OutputStream out=clientSocket.getOutputStream();//clientSocket调用getOutputStream()返回输出流

                inData =new DataInputStream(in);

                outData = new DataOutputStream(out);

                read.setDataInputStream(inData);

                read.setDataOutputStream(outData);

                thread.start();  //启动负责读信息的线程

            }

        }

        catch(Exception e) {

            System.out.println("服务器已断开"+e);

        }

    }

}

class Read implements Runnable {

    Scanner scanner = new Scanner(System.in);

    DataInputStream in;

    DataOutputStream out;

    public void setDataInputStream(DataInputStream in) {

        this.in = in;

    }

    public void setDataOutputStream(DataOutputStream out) {

        this.out = out;

    }

    public void run() {

        System.out.println("输入一个整数:");

        try{

                int n=scanner.nextInt();

                out.writeInt(n);

                double s=in.readDouble();

                System.out.println("客户端获得结果是"+s);

                Thread.sleep(500);

        }

        catch(Exception e) {}

    }

}

服务器端:

package Text4;

import java.io.*;

import java.net.*;

import java.util.*;

public class ServerItem {

    public static void main(String args[]) {

        ServerSocket server=null;

        ServerThread thread;

        Socket you=null;

        while(true) {

            try{  server= new ServerSocket(4331);//创建在端口4331上负责监听的 ServerSocket对象

            }

            catch(IOException e1) {

                System.out.println("正在监听");

            }

            try{  System.out.println("正在等待客户");

                you= server.accept(); // server调用accept()返回和客户端相连接的Socket对象

                System.out.println("客户的地址:"+you.getInetAddress());

            }

            catch (IOException e) {

                System.out.println(""+e);

            }

            if(you!=null) {

                new ServerThread(you).start();

            }

        }

    }

}

class ServerThread extends Thread {

    Socket socket;

    DataInputStream in=null;

    DataOutputStream out=null;

    ServerThread(Socket t) {

        socket=t;

        try  { out=new DataOutputStream(socket.getOutputStream());

            in=new DataInputStream(socket.getInputStream());

        }

        catch (IOException e) {}

    }

    public void run() {

        try{

            int n=in.readInt();

            System.out.println("服务器接收到的整数是"+n);

            double s=0;

            for(int i=1;i<=n;i++)

            {

                int p=i;

                double Mul=1;

                while(p>=1){

                    Mul*=p;

                    p--;

                }

                s+=Mul;

            }

            out.writeDouble(s);

            Thread.sleep(500);

        }

        catch(Exception exp){}

    }

}

 

 

 

 

 

 

 

  • 4
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值