[Java实验]七多线程程序设计 八

【题目】实验 7 多线程程序设计

       1、 编写一个程序,其功能是运行之后,其中有一个线程可以输出 20 次你的学号,另一 个线程会输出 20 次你的姓名。

【代码】

class XianC1 implements Runnable {
 public XianC1() {
        //构造函数
    }
    public void run() {
        for (int i = 1; i <= 20; i++) {
            System.out.println("第" + i + "次执行线程"
                    + Thread.currentThread().getName());
            try {
                Thread.currentThread().sleep(200);// 睡眠500ms
            } catch (InterruptedException e) {
            }  }  }
    public static void main(String args[]) {
        Thread t1 = new Thread(new XianC1(), "2100000000");// 创建线程1的对象,并
        // 通过第二个参数将其命名为 "
        Thread t2 = new Thread(new XianC1(), "娃哈哈"); // 创建线程2的对象,并
        // 通过第二个参数将其命名为 
        t1.start(); // 启动两个线程运行
        t2.start();
    }  }

【题目】实验 7 多线程程序设计

2、 编写一个图形界面程序,运行之后,让其中有一个线程能在界面上“实时”显示系 统当前时间(精确到秒获取时间可查询 java.util.Calendar 类,它包含了多个用于获得系统时 间的函数)。另让一个线程可以在界面上提示当前系统时间下用户该做什么工作(例如当程 序判断出系统时间现在是 8:00 到 9:00,则提示用户该上课;现在是 23:00 到 8:00,则 提示用户该休息。具体测试时可以将时间段限制到秒级,以便及时查看到程序运行中提示信 息的变化)。还可以选择尝试在到达特定时刻后播放闹铃(了解 Java 中播放声音的 API), 对用户进行提示。

【代码】

import javax.swing.*;
import java.util.Calendar;
public class XianC2 {
    static JFrame jf = new JFrame("java实验七:线程");
    static JTextField jta1;static JTextField jta2;
    static JTextField jta3;static JTextField jta4;
    static JTextField jta5;static JTextField jta6;
    static JTextField jta7;
    JLabel a;JLabel b;JLabel time;JLabel things;
    JLabel year;JLabel month;JLabel day;
    JLabel hour;JLabel minute;JLabel second;
    Thread trda = new thread11();
    public XianC2()
    {
        jf.setLayout(null);jf.setSize(400,400);
        jta1 = new JTextField("",100);jta2 = new JTextField("",170);
        a=new JLabel("现在的时间是:");b=new JLabel("我现在应该要:");
        a.setSize(100,40);b.setSize(100,40);
        jta1.setSize(200,30);jta2.setSize(200,30);
        a.setLocation(40,95);b.setLocation(40,295);
        jta1.setLocation(150,100);jta2.setLocation(150,300);
        jf.add(jta1);jf.add(jta2);jf.add(a);jf.add(b);
        jta1.setEditable(false);
        jta2.setEditable(false);
        jf.setVisible(true);
        trda.start(); //启动线程trda
    }
    public static void main(String args[]) {
        XianC2 frm = new XianC2();
    } }
class thread11 extends Thread //线程一,获取系统的时间,并将时间传给线程二
{public void run() {
    int y, m, d, h, mi, s;  thread22 thrd;
    for(;;){
        Calendar cal = Calendar.getInstance();
        y = cal.get(Calendar.YEAR);
        m = cal.get(Calendar.MONTH)+1;
        d = cal.get(Calendar.DATE);
        h = cal.get(Calendar.HOUR_OF_DAY);
        mi = cal.get(Calendar.MINUTE);
        s = cal.get(Calendar.SECOND);
        XianC2.jta1.setText(Integer.toString(y)+"/"+Integer.toString(m)+"/"+Integer.toString(d)+"  "+Integer.toString(h)+":"+Integer.toString(mi)+":"+Integer.toString(s));
        double se=(double)s;
        thrd=new thread22(se);
        thrd.start();
        try {
            Thread.sleep(1000);       }
        catch (InterruptedException e) {                  }    }
}           }
class thread22 extends Thread
{
    double s;thread22(double second){
    s=second;   }
    public void run() {
        if(s>=0  &&  s<5){
            XianC2.jta2.setText("起床啦");
        }
        else if((s>=5&&s<=10) ){
            XianC2.jta2.setText("吃早餐啦");
        }
        else if((s>10&& s <=15 )){
            XianC2.jta2.setText("早读啦");
        }
        else if(s>15 && s<20){
            XianC2.jta2.setText("上课啦");
        }
        else if(s>=20 && s<25){
            XianC2.jta2.setText("吃午饭啦");
        }
        else if(s>=25 && s<30){
            XianC2.jta2.setText("午休啦");
        }
        else if(s>=30 && s<35){
            XianC2.jta2.setText("上课啦");
        }
        else if(s>=35 && s<40){
            XianC2.jta2.setText("吃晚饭啦");
        }
        else if(s>=40 && s<45){
            XianC2.jta2.setText("写作业啦");
        }
        else if(s>=45 && s<50){
            XianC2.jta2.setText("写java啦");
        }
        else if(s>=50 && s<55){
            XianC2.jta2.setText("做实验啦");
        }
        else {
            XianC2.jta2.setText("休息啦");
        }
    }

【测试结果】

 

 

【题目】实验 8 网络通信程序设计

1、先熟悉所给的示例,了解网络编程的一般基本概念。然后两个同学为一组,分别设 计一对控制台下的 TCP 通信程序的客户端和服务器端,然后双方要能够相互发送和反馈信 息进行无限次连续通信,直到其中一方发送表示结束通信的“end”字符串,然后接收方也 返回一个“end”,双方结束通信。 若可能的话,建议最好设计出图形界面下的程序(即设计成一个简单的网络聊天程序)。 可在本地机上做测试,或两个同学为一组在不同的机器上作测试都可以,要将服务器地址和 端口号作为参数,在运行中可以进行修改。对于本机上测试,服务器地址使用 127.0.0.1 或者 本机实际 IP 地址。在网内不同机器上测试,要给出正确的服务器 IP 地址或名称。(部分电 脑可能要关闭防火墙才能实现局域网访问)

【代码】

客户端:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
public class KeHu {
    public static void main(String args[]) throws IOException
    {
        Socket socket1=new Socket("127.0.0.1",2288);
        Scanner sc=new Scanner(System.in);
        try
        {
            System.out.println("connection to server accepted:"+socket1);
            while(true){
                PrintWriter out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket1.getOutputStream())),true);// 下面向服务器输出数据
                String strr=sc.next();
                out.println(strr);
                // 下面接收服务器反馈过来的数据
                BufferedReader in=new BufferedReader(new InputStreamReader(socket1.getInputStream()));
                String str=in.readLine();// 获取对输入流(即网络上传来的数据流)的控制
                System.out.println(str);
                if(strr.equals("end") && str.equals("end"))
                    break;
            }
        }
        finally
        {
            System.out.println("client closing socket");
            socket1.close();
        }

    }
}

 服务器端:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class FuWuq
{
    public static void main(String args[]) throws IOException
    {
        ServerSocket s=new ServerSocket(2288);
        System.out.println("serversocket:"+s);
        Scanner sc=new Scanner(System.in);
        try
        {
            Socket socket1=s.accept();
            try
            {
                System.out.println("connection to client accepted:"+socket1);
                while(true){
                    BufferedReader in=new BufferedReader(new InputStreamReader(socket1.getInputStream()));
                    PrintWriter out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket1.getOutputStream())),true);
                    String str=in.readLine();
                    System.out.println("服务器端接收到客户端的数据是:"+str);
                    String strr=sc.next();
                    out.println(strr);
                    if(strr.equals("end") && str.equals("end"))
                        break;
                }
            }
            finally
            {
                System.out.println("server closing socket");
                socket1.close();
            }

        }
        finally
        {
            s.close();
        }
    }
}

【测试结果】

客户端:

 

 服务器端:

 2、应用上次实验中学到的多线程程序设计知识,设计个了解软件,让一台计算机作为 服务器,运行服务器程序,可以通过多线程响应多个客户端的连接和同学,并实现多个客户 端之间的通信。

【代码】

服务器:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class SimpleServer {
    public static Socket[] sockets = new Socket[100];
    public static void main(String[] args) throws Exception {
        ServerSocket serverSocket = new ServerSocket(10002);
        System.out.println("服务启动");
        int num = 0;
        while (true) {
            Socket socket = serverSocket.accept();

            System.out.println("服务连接");
            sockets[num] = socket;
            num++;
           
            new ServerThread(socket, sockets).start();
        }
    }
}
class ServerThread extends Thread {
    Socket client;
    int num;
    Socket[] sockets;
    BufferedReader br;
    public ServerThread(Socket client, Socket[] clients) throws Exception {
        super();
        this.client = client;
        this.sockets = clients;
        br = new BufferedReader(new InputStreamReader(this.client.getInputStream()));
    }
    public void run() {
        try {
            String content = null;
            while (true) {
                if ((content = br.readLine()) != null) {
                    for (int i=0;i<sockets.length;i++) {
                        if (sockets[i]!=null&&client != sockets[i]) {
                            PrintWriter printWriter = new
                                    PrintWriter(sockets[i].getOutputStream(), true);
                            printWriter.println(content);
                        }
                    }
                    System.out.println(content);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

客户1;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class Client1 {
    public static void main(String[] args) throws Exception {
        Socket client = new Socket("127.0.0.1", 10002);
        System.out.println("请您输入用户名:");
        BufferedReader bufferedReader = new BufferedReader(new
                InputStreamReader(System.in));
        String name = bufferedReader.readLine();
        System.out.println("欢迎" + name + "加入聊天室!");
        new ClientThread(client, name).start(); 
        InputStream is = client.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        while (true) {
            String msg = br.readLine();
            System.out.println(msg);
        }
    }
}
class ClientThread1 extends Thread {
    Socket client;
    String name;
    public ClientThread1(Socket client, String name) {
        this.name = name;
        this.client = client;
    }
    public void run() {
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            PrintWriter pw = new PrintWriter(client.getOutputStream(), true);
            while (true) {
                String msg = br.readLine(); 
                msg = name + ":" + msg; 
                pw.println(msg);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

注:客户2客户3只需将客户1 的类名更改一下即可代码一样,即将Client1改成Client2。

【测试结果】

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值