您好,欢迎来到划驼旅游。
搜索
您的当前位置:首页java多线程实验

java多线程实验

来源:划驼旅游
一、实验目的及要求

(1) 实验设计以前要求掌握数据库的相关知识,熟悉数据库方面的知识。 (1) 该系统应用多线程技术,并实现线程的同步

二、实验内容

(1) 设计一应用程序完成在线预约。 (2) 该系统客户方要求有友好的GUI。

(3) 该系统的服务器方要求使用多线程处理客户端信息。 (4) 所有用户和客户端信息匀存于后台数据中。 (5) DBMS可使用Microsoft Access 或 SQL Server。

3.主要仪器设备及软件:

(1) PC机

(2) Jbuilder或JDK1.5

三、实验主要流程、基本操作或核心代码、算法片段(该部分如不够填写,请填写至附页) 实验流程:在elipse 中建立一个GUI 工程,再建立两个公共类:client 和 server 客户端主程序:

import java.awt.*; import java.awt.event.*; import java.net.*; import java.io.*;

import java.util.Calendar; import java.awt.Dimension; import java.awt.Color; import java.awt.SystemColor; import java.awt.Font;

public class client extends Frame implements ActionListener{

private boolean login = false; boolean signal=false; private String rightNow;

private InetAddress clientAddress; private Socket connection; private DataInputStream in; private DataOutputStream out; private recThread receiver;

private Button B_login = new Button(\"登陆\");

private Button B_logout = new Button(\"断开连接\"); private Button B_send = new Button(\"预约\");

private Label userName = new Label(\"输入用户名:\"); private TextField getUserName = new TextField(); private Label svrIP = new Label(\"服务器IP:\"); private TextField getSvrIP = new TextField(); private Label svrPort = new Label(\"服务器端口:\"); private TextField getSvrPort = new TextField(); private Label goodtime = new Label(\"预约时间:\"); private TextField getGoodTime = new TextField(); private Label goodname = new Label(\"预约医生名字:\"); private TextField getGoodName = new TextField(); private Label goodid = new Label(\"预约医生编号:\"); private TextField getGoodId = new TextField(); private Label goodnum= new Label(\"预约科目:\"); private TextField getGoodNum = new TextField(); private TextArea input = new TextArea(); // @jve:decl-index=0:visual-constraint=\"95,39\" private TextArea output = new TextArea();

private class recThread extends Thread {

public recThread() {

start(); }

public void run() { try{

while(login){

String line = in.readUTF();

rightNow = Calendar.getInstance().getTime().toLocaleString(); if(line.charAt(0) == 'Q'){ // 退出 break; }

else if(line.charAt(0) == 'L'){

output.append(rightNow+\"\\n\"+line+\"\\n\\n\"); } }

}catch(SocketException se){

rightNow = Calendar.getInstance().getTime().toLocaleString(); output.append(rightNow+\"\\nConnection closed.\\n\\n\"); login = false;

getUserName.setEditable(true); getSvrIP.setEditable(true); getSvrPort.setEditable(true); B_login.setEnabled(true); B_send.setEnabled(false); B_logout.setEnabled(false); }catch (IOException ioe){

output.append(\"Error: \"+ioe+\"\\n\\n\"); } } }

// 响应关闭按钮的内部类

private class WindowCloser extends WindowAdapter {

public void windowClosing(WindowEvent we) {

System.exit(0); } } /**

* This method initializes this * */

private void initialize() {

B_send.setForeground(Color.blue); B_logout.setForeground(Color.blue); B_logout.setBackground(Color.lightGray); B_login.setForeground(Color.blue);

B_login.setBackground(new Color(204, 204, 255)); output.setBackground(SystemColor.activeCaptionBorder); output.setForeground(new Color(84, 84, 233)); input.setSize(new Dimension(439, 170));

input.setFont(new Font(\"Dialog\", Font.BOLD | Font.ITALIC, 12)); input.setForeground(new Color(255, 153, 255)); input.setBackground(Color.pink); this.setSize(new Dimension(123, 166)); this.setTitle(\"客户端\"); }

// 布局设置方法,在构造方法里面调用 private void setup()

{

Panel top1 = new Panel();

top1.setLayout(new BorderLayout()); top1.add(\"West\", userName); top1.add(\"Center\", getUserName);

Panel top2 = new Panel();

top2.setLayout(new BorderLayout()); top2.add(\"West\", svrIP); top2.add(\"Center\", getSvrIP);

Panel top3 = new Panel();

top3.setLayout(new BorderLayout()); top3.add(\"West\", svrPort); top3.add(\"Center\", getSvrPort);

Panel top4 = new Panel();

top4.setLayout(new BorderLayout()); top4.add(\"North\", top1); top4.add(\"Center\", top2); top4.add(\"East\", top3);

Panel top5 = new Panel();

top5.setLayout(new BorderLayout()); top5.add(\"West\", goodid); top5.add(\"Center\", getGoodId);

Panel top6 = new Panel();

top6.setLayout(new BorderLayout()); top6.add(\"West\", goodname); top6.add(\"Center\", getGoodName);

Panel top7 = new Panel();

top7.setLayout(new BorderLayout()); top7.add(\"West\", goodnum); top7.add(\"Center\", getGoodNum);

Panel top8 = new Panel();

top8.setLayout(new BorderLayout()); top8.add(\"West\", goodtime); top8.add(\"Center\", getGoodTime);

Panel top9 = new Panel();

top9.setLayout(new BorderLayout()); top9.add(\"North\", top7); top9.add(\"Center\", top8);

Panel top10 = new Panel();

top10.setLayout(new BorderLayout()); top10.add(\"North\", top5); top10.add(\"Center\", top6);

Panel east = new Panel();

east.setLayout(new BorderLayout()); east.add(\"North\", top9); east.add(\"Center\", top10);

Panel center = new Panel();

center.setLayout(new BorderLayout()); center.add(\"Center\", output); center.add(\"South\", east);

Panel south = new Panel();

south.setLayout(new FlowLayout()); south.add(B_login); south.add(B_logout); south.add(B_send);

setLayout(new BorderLayout()); add(\"North\", top4); add(\"Center\", center); add(\"South\", south); }

// 构造方法

public client()throws UnknownHostException, IOException {

super(\"客户端\");

login = false;

clientAddress = InetAddress.getLocalHost(); byte[] ip = clientAddress.getAddress();

initialize();

String strIP = (ip[0]&0xFF)+\".\"+(ip[1]&0xFF)+ \".\"+(ip[2]&0xFF)+\".\"+(ip[3]&0xFF); getSvrIP.setText(strIP); getSvrPort.setText(\"1234\"); getUserName.setText(\"User\");

output.setEditable(false); // 输出文本框设为只读属性 B_login.addActionListener(this); B_send.addActionListener(this); B_send.setEnabled(false);

B_logout.addActionListener(this); B_logout.setEnabled(false);

addWindowListener(new WindowCloser());

getUserName.setText(\"\"); setup(); pack();

setSize(400, 400); show();

rightNow = Calendar.getInstance().getTime().toLocaleString(); output.append(rightNow+\"\\n客户端开始!.\\n我的IP地址是 \"+strIP+\"\\n\\n\"); } // 登录

private void logIn() {

if(login) return;

boolean accepted = false, refused = false;

String line= new String(\"\"); try{

connection = new Socket(getSvrIP.getText(), Integer.parseInt(getSvrPort.getText()));

in = new DataInputStream(connection.getInputStream()); out = new DataOutputStream(connection.getOutputStream()); out.writeUTF(\"L \"+getUserName.getText()); while(!accepted && !refused){ line = in.readUTF(); if(line.charAt(0) == 'R'){

refused = true; }

if(line.charAt(0) == 'A'){ accepted = true; } }

if(refused){

rightNow = Calendar.getInstance().getTime().toLocaleString(); output.append(rightNow+\"\\n用户名错误!请重新输入!.\\n\\n\"); }

if(accepted){

rightNow = Calendar.getInstance().getTime().toLocaleString(); output.append(rightNow+\"\\n成功登陆!.\\n\\n\"); login = true;

getUserName.setEditable(false); getSvrIP.setEditable(false); getSvrPort.setEditable(false); B_login.setEnabled(false); B_send.setEnabled(true); B_logout.setEnabled(true); }

}catch(ConnectException ce){

rightNow = Calendar.getInstance().getTime().toLocaleString(); output.append(rightNow+\"\\n没有找到服务器!\\n\\n\"); }catch(UnknownHostException uhe){

rightNow = Calendar.getInstance().getTime().toLocaleString(); output.append(rightNow+\"\\n没有找到服务器!\\n\\n\"); }catch(IOException ioe){

output.append(\"Error: \"+ioe+\"\\n\\n\"); } }

// 发送消息

private void sendMsg()

{ String line1= new String(\"\"); boolean signal=false; if(!login) return; try{

out.writeUTF(\"医生编号:\"+getGoodId.getText()+\"\\n医生名称:

\"+getGoodName.getText()+\"\\n预约时间:\"+getGoodTime.getText()+\"\\n预约科目:\"+getGoodNum.getText()+\"\"); getGoodId.setText(\"\"); getGoodName.setText(\"\"); getGoodNum.setText(\"\"); getGoodTime.setText(\"\"); line1= in.readUTF(); if(line1.charAt(0)=='H'){ signal=true; }

if(signal){ }

// 退出登录

private void Quit() {

if(!login) return; try{

out.writeUTF(\"Q\"); connection.close();

rightNow = Calendar.getInstance().getTime().toLocaleString(); output.append(rightNow+\"\\n退出!\\n\\n\"); login = false;

getUserName.setEditable(true); getSvrIP.setEditable(true); getSvrPort.setEditable(true); B_login.setEnabled(true); B_send.setEnabled(false); B_logout.setEnabled(false); }catch (IOException ioe){

output.append(\"Error: \"+ioe+\"\\n\\n\"); } }

// 消息处理方法

public void actionPerformed(ActionEvent e) {

if(e.getSource() == B_login){ logIn(); }

rightNow=Calendar.getInstance().getTime().toLocaleString(); output.append(rightNow+\"\\n该医生此时间已有人预约,请另选时间预约!\\n\");

}

output.append(\"Error: \"+ioe+\"\\n\\n\"); }

}catch(IOException ioe){

if(e.getSource() == B_send){ sendMsg(); }

if(e.getSource() == B_logout){ Quit(); } }

// 主方法

public static void main(String args [])throws UnknownHostException, IOException {

client c = new client(); }

} // @jve:decl-index=0:visual-constraint=\"10,10\"

服务器程序:

import java.awt.*; import java.awt.event.*; import java.net.*; import java.io.*;

import java.util.Enumeration; import java.util.Hashtable; import java.util.Calendar; import java.sql.*;

import sun.jdbc.odbc.JdbcOdbc; import java.awt.Dimension; import java.awt.Rectangle; import javax.swing.JLabel; import java.awt.SystemColor; import java.awt.Color; import java.awt.BorderLayout;

public class Server extends Frame implements ActionListener{

private boolean serving = false; private String rightNow; private InetAddress svrAddress; private ServerSocket server; private ServerThread st; private String userName;

private Connection con=null;

private Statement stmt=null; private ResultSet rs=null;

private Label svrIP = new Label(\"服务器IP:\"); private TextField showSvrIP = new TextField(); private Label svrPort = new Label(\"服务器端口:\"); private TextField getSvrPort = new TextField(\"1234\"); private Button enter = new Button(\"Start\"); private TextArea output = new TextArea(); private JLabel jLabel = null;

private class WindowCloser extends WindowAdapter {

public void windowClosing(WindowEvent we) {

System.exit(0); } } /**

* This method initializes this * */

private void initialize() {

enter.setBounds(new Rectangle(363, 33, , 28)); svrIP.setBounds(new Rectangle(420, 200, 14, 105)); output.setBackground(new Color(153, 187, 244)); output.setBounds(new Rectangle(5, 67, 430, 235)); output.setForeground(Color.blue); jLabel = new JLabel(); jLabel.setText(\"IP地址为:\");

jLabel.setBackground(new Color(255, 153, 153)); jLabel.setForeground(Color.magenta);

jLabel.setBounds(new Rectangle(50, 28, 71, 28)); this.setLayout(null);

this.setSize(new Dimension(438, 309)); this.setBackground(Color.white);

this.setForeground(SystemColor.inactiveCaption); this.setTitle(\"服务器\"); this.add(output, null); this.add(svrIP, null); this.add(enter, null); this.add(jLabel, null);

}

private void setup() {

output.setSize(new Dimension(307, 170));

svrIP.setBounds(new Rectangle(503, 60, 72, 23)); output.setBounds(new Rectangle(11, 45, 440, 170)); Panel top = new Panel();

top.setLayout(new FlowLayout());

top.setBounds(new Rectangle(127, 30, 217, 33)); top.add(showSvrIP, showSvrIP.getName()); top.add(svrPort); top.add(getSvrPort);

setLayout(new BorderLayout()); add(\"North\", top); add(\"Center\", output); }

public Server()throws UnknownHostException, IOException {

super(\"Chat Room Server\");

serving = false;

svrAddress = InetAddress.getLocalHost(); byte[] ip = svrAddress.getAddress();

showSvrIP.setText((ip[0]&0xFF)+\".\"+(ip[1]&0xFF)+\".\" +(ip[2]&0xFF)+\".\"+(ip[3]&0xFF));

showSvrIP.setEditable(false); output.setEditable(false);

enter.addActionListener(this);

addWindowListener(new WindowCloser()); setup(); pack();

setSize(500, 400); show(); }

private class ServerThreadSingle extends Thread{ public Socket connection; private DataInputStream in;

initialize();

private DataOutputStream out; private boolean login;

private String driverDriverName=\"com.microsoft.sqlserver.jdbc.SQLServerDriver\"; private String dbURL=\"jdbc:sqlserver://localhost:1433; DatabaseName=Order\"; private String userName1 = \"sa\"; //默认用户名 // @jve:decl-index=0: private String userPwd = \"123\"; //密码 public ServerThreadSingle(Socket _connection){ try{

connection = _connection;

in = new DataInputStream(connection.getInputStream()); out = new DataOutputStream(connection.getOutputStream()); login = false;

userName = new String(\"\"); start();

}catch(IOException ioe){ output.append(\"Error: \"+ioe); } }

public void run(){ try{

Class.forName(driverDriverName);

con = DriverManager.getConnection(dbURL, userName1, userPwd); stmt=con.createStatement();

String line = new String(\"Q\"); while(!login){ if(!serving) break;

line = in.readUTF();

if(line.charAt(0) == 'L'){ userName = line.substring(2);

rs=stmt.executeQuery(\"select * from users where username='\"+userName+\"'\"); if(!rs.next()){ out.writeUTF(\"R\"); break; } }

line = \"A\";

out.writeUTF(line);

rightNow = Calendar.getInstance().getTime().toLocaleString(); output.append(rightNow+\"\\n\"+userName+\" 登陆.\\n\\n\"); }

login = true;

while(login){ line = in.readUTF();

if(!serving) break; if(line.charAt(0)=='Q'){

output.append(rightNow+\"\\n\"+userName+\" 退出!\"); login = false; } else{

//一下是读信息

rightNow = Calendar.getInstance().getTime().toLocaleString(); line=line.substring(0);

String line0=line.substring(2);

rs=stmt.executeQuery(\"select * from hinfo where information='\"+line+\"'\"); if(rs.next()){ out.writeUTF(\"H\");} else{

output.append(rightNow+\"\\n\"+userName+\" 预约\\"+line+\"\\n\\n\"); String str=new String(rightNow+\"\\n\"+userName+\" 预约\\"+line); stmt.executeUpdate(\"insert into hinfo values('\"+line+\"')\"); stmt.executeUpdate(\"insert into infm values('\"+str+\"')\"); } } }

in.close(); out.close(); connection.close(); }catch(SocketException se){

output.append(\"\"+userName+\" 退出连接!\\n\"); }catch(IOException ioe){

if(!(ioe instanceof EOFException)){ output.append(\"Error: \"+ioe+\"\\n\\n\"); }

} catch (ClassNotFoundException e) { } } }

// 用于接受客户连接请求的线程类

private class ServerThread extends Thread{ private boolean running; public ServerThread()

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

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

} catch (SQLException e) {

{

start(); }

public void run() { try{

while(serving){

Socket connection = server.accept(); ServerThreadSingle handler

= new ServerThreadSingle(connection); }

}catch(SocketException se){

rightNow = Calendar.getInstance().getTime().toLocaleString(); output.append(rightNow+\"\\n服务停止!\\n\\n\"); }catch(IOException ioe){

output.append(\"Error: \"+ioe+\"\\n\\n\"); } } }

// 消息处理方法

public void actionPerformed(ActionEvent event) {

if(event.getSource() == enter) {

if(serving){ try{

serving = false; server.close();

enter.setLabel(\"Start\"); }catch(SocketException se){

rightNow = Calendar.getInstance().getTime().toLocaleString(); output.append(rightNow+\"\\n服务停止!\\n\\n\"); }catch(IOException ioe){

output.append(\"Error: \"+ioe+\"\\n\\n\"); } }

else{ try{

server = new ServerSocket(Integer.parseInt(getSvrPort.getText())); rightNow = Calendar.getInstance().getTime().toLocaleString(); output.append(rightNow+\"\\n服务开始!.\\n\\n\"); enter.setLabel(\"Stop\"); st = new ServerThread(); serving = true;

}catch(IOException ioe){

output.append(\"Error: \"+ioe+\"\\n\\n\"); } } } }

// 主方法

public static void main(String args [])throws UnknownHostException, IOException {

Server s = new Server(); } }

四、实验结果的分析与评价(该部分如不够填写,请填写至附页) 实验结果:

注:实验成绩分为(90——100分)优,(80——分)良,(70——79)中,(60——69分)及格,(59分)不及格。

分析: 在此实验中运用了Button的控件来向服务器发送消息,因而也要写它的响应事件,该试验通过利用线程来实现用户点击不同按钮时,启动服务器的线程来访问数据库,从而可以实现在点击时,时间的重合性,实现用户的预约。通过该试验了解了计算机中线程的应用和功能!同时还知道了访问数据库的方法。

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- huatuo6.com 版权所有 湘ICP备2023023988号-11

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务