前言

代码仅供复习查看,只收集整理了重要知识点

仅个人能看懂不保证能正常运行

具体怎么实现还得看基本功了

Comparable接口实现排序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class TCountry implements Comparable{	
int GoldNum;
int SilverNum;
int BronzeNum;
public int compareTo(Object o) {
TCountry obj = (TCountry)o;
if(this.GoldNum != obj.GoldNum) {
return -this.GoldNum + obj.GoldNum; //具体怎么减可以输出看一下
}
if(this.GoldNum == obj.GoldNum && this.SilverNum != obj.SilverNum) {
return -this.SilverNum + obj.SilverNum;
}
else {
return -this.BronzeNum + obj.BronzeNum;
}
}
/* //main函数用
Country lst[] = {c1,c2,c3,c4,c5,c6,c7,c8,c9}; //先放入数组中
//只要实现Comparable接口
Arrays.sort(lst); //调用Arrays类的sort方法
*/
}

日历类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package work2;

import java.util.Calendar;

public class TMyCalendar {

//Calendar类的roll函数不影响其他变量,但是add函数影响
//利用这一点,可以用roll函数回滚求一个月有几天
//然后用add函数实现题目要求,输出不同月份的日历

void ShowMyCalendar(int Difference) { //参数Difference为要求的月差
Calendar cal = Calendar.getInstance(); //获取现在时间

cal.add(Calendar.MONTH, Difference); //用于增加月,并且影响其他变量
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
cal.set(Calendar.DAY_OF_MONTH,1);
int day = cal.get(Calendar.DAY_OF_MONTH);
int day_w = cal.get(Calendar.DAY_OF_WEEK); //是一周内的第几天,1-7
cal.roll(Calendar.DAY_OF_MONTH,false); //回滚,可以用来求一个月有几天
int daynum = cal.get(Calendar.DAY_OF_MONTH);
System.out.println(year + "年" + (month+1) + "月");
System.out.println("\t日\t一\t二\t三\t四\t五\t六\t");
this.PrintSpace(day_w); //打印空格函数,用于第一个数字的输出
for(int i=0;i<daynum;i++) { //一个月天数输出
if(day_w != 8) {
System.out.print(day+"\t");
}
else {
day_w = 1;
System.out.println();
System.out.print("\t"+day+"\t");
}
day++;
day_w++;
}
}
void PrintSpace(int day_w) {
System.out.print("\t");
if(day_w == 2) {
for(int i=0;i<1;i++) {
System.out.print("\t");
}
}
if(day_w == 3) {
for(int i=0;i<2;i++) {
System.out.print("\t");
}
}
if(day_w == 4) {
for(int i=0;i<3;i++) {
System.out.print("\t");
}
}
if(day_w == 5) {
for(int i=0;i<4;i++) {
System.out.print("\t");
}
}
if(day_w == 6) {
for(int i=0;i<5;i++) {
System.out.print("\t");
}
}
if(day_w == 7) {
for(int i=0;i<6;i++) {
System.out.print("\t");
}
}
if(day_w == 1) {
}
}
}

自定义异常类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class TMyException {

/* //异常自己写,比如
*
* public class InsufficientFundsException extends Exception {

public InsufficientFundsException(String str) { //构造函数传参为字符串
super(str); //在产生异常时可以输出此字符串
}
}
*
void deposite(int dAmount) throws NegativeAmountException{ //函数后throw就行
if(dAmount < 0) {
throw new NegativeAmountException("存入数据非法: " + dAmount); //当做对象new
}

this.amount += dAmount;
System.out.println("存入"+dAmount+", 当前金额: "+this.amount);
}
*/
}

txt文件复制

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
public class TTXTCopy {
File Poem1;
File Poem2;
File newPoem;

TTXTCopy(){ //用FileWriter和Reader实现txt复制
Poem1 = new File(".\\files\\poem\\Poem1.txt");
Poem2 = new File(".\\files\\poem\\Poem2.txt");
newPoem = new File(".\\files\\poem\\李白诗集.txt");
if(!newPoem.exists()) { //判断文件存在
try {
newPoem.createNewFile(); //不存在就创建
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
int n=0;
char buf[] = new char[10]; //char的数组
try {
FileReader FR = new FileReader(Poem1);
FileWriter FW = new FileWriter(newPoem);
while((n = FR.read(buf)) != -1) { //读进buf
FW.write(buf,0,n); //要写n个,不然会出现重复现象
}
FW.write("\n\n"); //新写入内容
FR.close(); //记得关

FR = new FileReader(Poem2);
while((n = FR.read(buf)) != -1) {
FW.write(buf,0,n);
}
FW.write("\n\t\t\t\t————李白诗集");

FR.close();
FW.close(); //好习惯:关文件
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("创建完成");
}

public static void main(String[] args) {
// TODO Auto-generated method stub

}

}

文件复制

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
public class TFileCopy {

File Source;
File Dest;

TFileCopy() {
Source = new File(".\\source");
Dest = new File(".\\dest");

}

void ShowList() { //打印目录
String[] lst = Source.list(); //获得目录下文件数组
for(int i=0;i<lst.length;i++) {
System.out.println(lst[i]);
}
}

void Copy_FileInOutputStream(String name) { //用FIS和FOS实现文件复制
File obj = new File(Source, name); //在指定的Source目录下的文件
if(!obj.exists()) {
System.out.println("File doesn't exist: " + name);
return;
}
else {
try {
File result = new File(Dest, name); //在指定的Dest目录下的文件
if(!result.exists()) {
result.createNewFile(); //不存在就创建
}
FileInputStream FIS = new FileInputStream(obj); //类似于FW和FR
FileOutputStream FOS = new FileOutputStream(result);
int n=0;
byte buf[] = new byte[10]; //byte数组
while((n = FIS.read(buf)) != -1) {
FOS.write(buf,0,n);
}
System.out.println(name+" copied successfully");
FIS.close();
FOS.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
void CopyFolder(String FileName, String DestName, String ParentFileName) { //递归复制文件夹和文件
File obj = new File(ParentFileName + "\\" + FileName);
File result = new File(DestName + "\\" + FileName);
if(obj.isDirectory()) { //如果是文件夹,就在目标地方创建文件夹,并对原始文件夹内所有文件递归调用此函数
result.mkdir();
System.out.println("Folder: " + FileName + " copied successfully");
String lst[] = obj.list();
for(int i=0;i<lst.length;i++) {
CopyFolder(lst[i], DestName+"\\"+FileName, ParentFileName + "\\" +FileName);
}
return;
}
else { //如果是文件,就调用复制函数,这个是直接修改Copy_FileInOutputStream而来的
try {
if(!result.exists()) {
result.createNewFile();
}
FileInputStream FIS = new FileInputStream(obj);
FileOutputStream FOS = new FileOutputStream(result);
int n=0;
byte buf[] = new byte[10];
while((n = FIS.read(buf)) != -1) {
FOS.write(buf,0,n);
}
System.out.println("File: " + FileName+" copied successfully");
FIS.close();
FOS.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return;
}
}
void CopyFolderTo(String FileName, String DestName) { //为了实现把files文件夹的内容复制到filescopy文件夹
//而不是把files文件夹整个放入filescopy内
File obj = new File(FileName);
String lst[] = obj.list();
for(int i=0;i<lst.length;i++) {
CopyFolder(lst[i], ".\\filescopy", ".\\files");
}
System.out.println("All files copied successfully");
}
void Operation() { //在控制台进行操作
while(true) { //死循环
System.out.print("Please input a command: ");
Scanner reader = new Scanner(System.in);
String operation = reader.nextLine(); //读nextLine
if(operation.equals("list")) { //显示路径下文件
ShowList();
}
else if(operation.equals("exit")) { //退出
System.out.println("System exits.");
break;
}
else {
String name = operation.substring(5);
operation = operation.substring(0, 4); //对命令处理,得到命令和文件名
if(operation.equals("copy")) {
Copy_FileInOutputStream(name);
}
else {
System.out.println("Wrong command");
}
}
System.out.println("");
}
}
}

数据库操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
public class TDBOperation {

//先给工程添加数据库的jar包
//右键工程->Build Path->Add External Archives
//找到mysql的jar包:mysql-connector-java-8.0.22.jar
//工程左边的相关库中出现mysql的jar包即可

//新建数据库,字符集选utf8 -- UTF-8 Unicode
//排序规则选utf8_general_ci
Connection con;
Statement sql;

public TDBOperation() { //用构造函数连接数据库
// TODO Auto-generated constructor stub
this.con = null;
this.sql = null;

//加载驱动
try {
Class.forName("com.mysql.cj.jdbc.Driver");
System.out.println("加载驱动成功");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("加载驱动失败");
}

//建立连接
String url = "jdbc:mysql://localhost:3306/test?"
+ "&useSSL=false"
+ "&characterEncoding=UTF-8"
+ "&serverTimezone=UTC";
String user = "root";
String password = "123"; //会提供
try {
con = java.sql.DriverManager.getConnection(url,user,password);
System.out.println("连接成功");
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("连接失败");
e.printStackTrace();
}
}
void InsertData() { //插入数据
//生成statement对象
try {
if(this.sql == null) {
sql = con.createStatement();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//应该要先在Navicat里建立对应表
//字符串类型选varchar
//注意选key值
//最后保存
//此代码内表名为employee,内容有id,name,sex,salary

String InsertStatement1 = "insert into employee (id,name,sex,salary) values (1002,'Tom','male',2600)";
String InsertStatement2 = "insert into employee (id,name,sex,salary) values (1003,'Mary','female',3200)";
String InsertStatement3 = "insert into employee (id,name,sex,salary) values (1004,'Peter','male',3000)";
String InsertStatement4 = "insert into employee (id,name,sex,salary) values (1005,'John','male',7000)";
String InsertStatement5 = "insert into employee (id,name,sex,salary) values (1006,'Paul','male',4000)";
//用Statement控制数据库
try {
sql.executeUpdate(InsertStatement1);
sql.executeUpdate(InsertStatement2);
sql.executeUpdate(InsertStatement3);
sql.executeUpdate(InsertStatement4);
sql.executeUpdate(InsertStatement5);
System.out.println("插入成功");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
void UpdataAllSalary(int add) { //给全体的某项加值
try {
if(this.sql == null) {
sql = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String AddStatement = "update employee set salary=salary+" + add;
try {
sql.executeUpdate(AddStatement);
System.out.println("所有人工资加" + add);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
void DeletePeter() {
try {
if(this.sql == null) {
sql = con.createStatement();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
String DeleteStatement = "delete from employee where name='Peter'";
sql.executeUpdate(DeleteStatement);
System.out.println("所有Peter已被开除");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

void Search() { //查询工资>=4000
try {
if(this.sql == null) {
sql = con.createStatement();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
ResultSet rs = null; //开一个resultset
String SearchStatement = "select * from employee where salary>=4000";
rs = sql.executeQuery(SearchStatement);
while(rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String sex = rs.getString("sex");
int salary = rs.getInt("salary");
System.out.println("ID: " + id + " Name: " + name + " Sex: " + sex + " Salary: " + salary);
}
System.out.println("成功输出所有工资大于等于4000");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
void DeleteAll() { //删库
try {
if(this.sql == null) {
sql = con.createStatement();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
String DeleteAllStatement = "delete from employee";
sql.executeUpdate(DeleteAllStatement);
System.out.println("全部删除");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
void CloseConnection() {
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
TDBOperation test = new TDBOperation();
test.InsertData();
test.Search();
test.UpdataAllSalary(1500);
test.DeletePeter();
//test.DeleteAll();
test.CloseConnection(); //记得关闭connection
}

}

数据库查找界面

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
public class TDBFrame extends JFrame{

JButton B1;
JButton B2;
JTextField T1;
JTextField T2;
JTextField T3;
JTextField T4;

DB_Check Checker = new DB_Check(); //新建一个类写,这个是程序的重点

ActionListener ButtonListener = new ActionListener() { //匿名类

@Override
public void actionPerformed(ActionEvent e) { //点击一次按钮进行一次数据库操作
//数据库用作成员变量,仅初始化一次
if(e.getSource() == B1) {
String ID = T1.getText();
String name;
int price;
String date;
try { //注意单双引号
String SearchStatement = "select * from product where productID='" + ID +"'";
ResultSet rs = Checker.sql.executeQuery(SearchStatement);
rs.next(); //因为rs一开始指在表前,要next一下
name = rs.getString("name");
price = rs.getInt("price");
date = rs.getString("date");
T2.setText(name);
T3.setText("" + price);
T4.setText(date);
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
if(e.getSource() == B2) {
T1.setText("");
T2.setText("");
T3.setText("");
T4.setText("");
}
}
};
TDBFrame(){
Init();
setSize(550,450);
setLocationRelativeTo(null);
setTitle("汽车信息查询");
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
void Init() {
setLayout(null);
//正常布局,挺容易,剩下自己写
}
public class DB_Check { //新建一个类,此处用作类中类
Connection con;
Statement sql;

public DB_Check() {
// TODO Auto-generated constructor stub
this.con = null;
this.sql = null;

//加载驱动
try {
Class.forName("com.mysql.cj.jdbc.Driver");
System.out.println("加载驱动成功");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("加载驱动失败");
}

//建立连接
String url = "jdbc:mysql://localhost:3306/test?"
+ "&useSSL=false"
+ "&characterEncoding=UTF-8"
+ "&serverTimezone=UTC";
String user = "root";
String password = "123";
try {
con = java.sql.DriverManager.getConnection(url,user,password);
System.out.println("连接成功");
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("连接失败");
e.printStackTrace();
}

//创建statement
try {
sql = con.createStatement();
System.out.println("已创建statement");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new TDBFrame();
}

}


多线程文件复制

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
public class TThreadCopy extends Thread{	//线程实现方法之一:继承thread类

String name; //用于文件复制,可以用作线程类里的变量
TThreadCopy(String name){
super("复制"); //线程构造函数要调super, 写第一行
this.name = name;
}
TThreadCopy(){
super("复制");
this.name = "";
}
public void run() { //线程的run方法,在里面实现功能
File source = new File(".\\source");
File obj = new File(source,name);
if(!obj.exists()) {
System.out.println("文件"+name+"不存在");
return;
}
File dest = new File(".\\dest");
File result = new File(dest,name);
if(!result.exists()) {
try {
result.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
FileInputStream FIS = new FileInputStream(obj);
FileOutputStream FOS = new FileOutputStream(result);
int n=0;
byte buf[] = new byte[10];
while((n = FIS.read(buf)) != -1) {
FOS.write(buf,0,n);
}
System.out.println(name+" copied successfully");
FIS.close(); //记得关文件
FOS.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
File source = new File(".\\source");
String[] lst = source.list();
TThreadCopy[] ThreadList = new TThreadCopy[lst.length]; //建立线程数组
for(int i=0;i<lst.length;i++) {
ThreadList[i] = new TThreadCopy(lst[i]);//文件名当参数传入线程构造函数
}
for(int i=0;i<lst.length;i++) {
ThreadList[i].start(); //实现run方法的线程直接start
}
}
}

多线程卖票

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
public class TThreadWorkShop implements Runnable{	//线程实现方法之二:实现Runnable接口

int total = 800; //卖票问题
@Override
public void run() {
// TODO Auto-generated method stub
int num=0;
while(total>0) {
try {
Thread.sleep(10); //线程等待
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized (this) { //synchronized方法,确保同一时刻只有一个线程在修改当前对象
if(total>0) { //获取当前线程名
System.out.println(Thread.currentThread().getName() + "卖出第" + total + "张票");
total--;
num++;
}
}
}
System.out.println(Thread.currentThread().getName()+"总共卖出"+num+"张票");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
TThreadWorkShop Target = new TThreadWorkShop(); //runnable接口为线程第一个参数
Thread WorkThread1 = new Thread(Target,"WorkShop1");
Thread WorkThread2 = new Thread(Target,"WorkShop2");
Thread WorkThread3 = new Thread(Target,"WorkShop3");
Thread WorkThread4 = new Thread(Target,"WorkShop4");
WorkThread1.start();
WorkThread2.start();
WorkThread3.start();
WorkThread4.start();
}
}

多线程经典生产者消费者问题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
package work7;

public class TThreadProducer_Consumer {

public static void main(String[] args) {
GoodsShelf Shelf = new GoodsShelf();
Producer p1 = new Producer("生产者1");
Producer p2 = new Producer("生产者2");
Consumer c1 = new Consumer("消费者1");
Consumer c2 = new Consumer("消费者2");
Consumer c3 = new Consumer("消费者3");
p1.setShelf(Shelf);
p2.setShelf(Shelf);
c1.setShelf(Shelf);
c2.setShelf(Shelf);
c3.setShelf(Shelf);
p1.start();
p2.start();
c1.start();
c2.start();
c3.start();

}
}

public class Consumer extends Thread{ //生产者消费者为线程

GoodsShelf Shelf; //为变量,通过设置函数,让生产者消费者指向同一个shelf
public Consumer(String name) {
// TODO Auto-generated constructor stub
super(name);
}
void setShelf(GoodsShelf Shelf) {
this.Shelf = Shelf;
}
void Consume() {
Shelf.remove(); //调用货架拿物品函数,此函数为synchronized方法
try {
Thread.sleep(7000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void run() {
while(true) {
Consume();
}
}
}
public class Producer extends Thread{ //生产者消费者为线程
GoodsShelf Shelf;

public Producer(String name) {
// TODO Auto-generated constructor stub
super(name);
}
void setShelf(GoodsShelf Shelf) { //通过设置函数,让生产者消费者指向同一个shelf
this.Shelf = Shelf;
}
void Produce() {
Shelf.add(new Goods()); //调用货架放物品函数,此函数为synchronized方法
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void run() {
while(true) {
Produce();
}
}
}
public class GoodsShelf {
Goods Shelf[];
int index;
int DefaultSize;
public GoodsShelf() {
// TODO Auto-generated constructor stub
DefaultSize = 10;
Shelf = new Goods[DefaultSize];
index = -1;
}
boolean IsEmpty() {
return index == -1;
}
boolean IsFull() {
return index == DefaultSize-1;
}
synchronized void add(Goods goods) { //加物品:synchronized方法
while(IsFull()) { //如果货架满了
try {
System.out.println("货架已满,"+Thread.currentThread().getName()+"无法继续生产");
this.wait(); //无法放货物,则等待
} catch (InterruptedException e) {
e.printStackTrace();
}
}
index++;
Shelf[index] = goods;
System.out.println(Thread.currentThread().getName()+"添加了新商品");
notifyAll(); //唤醒所有
}
synchronized void remove() { //拿物品:synchronized方法
while(IsEmpty()) {
try {
System.out.println("货架已空,"+Thread.currentThread().getName()+"无法购买");
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
index--;
System.out.println(Thread.currentThread().getName()+"购买了商品");
notifyAll();
}
}


文件复制客户端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
public class TFileCopyClient {

Socket socket = null; //客户端和服务器都得有socket
DataInputStream DIS = null; //DIS和DOS用于socket之间通信
DataOutputStream DOS = null;
FileOutputStream FOS = null; //FOS用于写文件

public TFileCopyClient() { //客户端不用建立多线程
try { //在构造函数里初始化socket, DIS, DOS
socket = new Socket("127.0.0.1",2018); //可以不用ISA, 直接初始化socket,指定IP和端口
System.out.println("连接服务器成功");
DIS = new DataInputStream(socket.getInputStream());
DOS = new DataOutputStream(socket.getOutputStream());
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
System.out.println("连接服务器失败");
}
}
void getFileNames() {
try {
int len = DIS.readInt(); //读服务器端发送的文件数目
System.out.println("文件名如下: ");
for(int i=0;i<len;i++) {
System.out.println(DIS.readUTF()); //显示文件夹内文件名(从服务器端接收)
}
} catch (IOException e) {
e.printStackTrace();
}
}
void Interact() { //客户端与服务器端发送接受一一对应
getFileNames(); //先读服务器发来的文件夹内容
Scanner scanner = new Scanner(System.in);
File DestFolder = new File(".\\destination");
File result = null;
while(true) { //循环
try {
System.out.println("请输入一个文件名");
String name = scanner.nextLine(); //从控制台读文件名
DOS.writeUTF(name); //给服务器端写文件名
if(DIS.readBoolean() == false) { //从服务器读一个布尔
//如果是假,说明文件不存在,无法复制
System.out.println("文件不存在,无法复制");
continue;
}
result = new File(DestFolder,name);
result.createNewFile();
FOS = new FileOutputStream(result); //初始化FOS
int n = 0;
byte buf[] = new byte[10000];
while((n = DIS.readInt()) != -1) { //注意要从服务器端再写一次-1,满足循环结束条件
DIS.read(buf);
FOS.write(buf,0,n);
DOS.writeInt(1); //为防止文件过小而加入的服务器客户端应答机制
}
System.out.println(name + " copied successfully");
FOS.close(); //记得关文件
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
new TFileCopyClient().Interact();
}
}

文件复制服务器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
public class TFileCopyServer {		//服务器要有sSocket
ServerSocket sSocket; //服务器的socket放在多线程里
File SourceFolder = null;
String lst[] = null;
TFileCopyServer() {
try {
sSocket = new ServerSocket(2018); //初始化sSocket, 指定端口2018
SourceFolder = new File(".\\source"); //文件夹,用于传递文件名
lst = SourceFolder.list();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
class ClientThread extends Thread { //处理客户端线程,类中类
Socket socket = null; //通信的socket放在这里
DataInputStream DIS = null;
DataOutputStream DOS = null;
FileInputStream FIS = null;
File obj = null;
ClientThread(Socket socket){ //构造函数把socket放进来
super(); //调用super()
this.socket = socket; //指定参数socket为线程的socket
try {
DIS = new DataInputStream(socket.getInputStream()); //初始化DIS,DOS
DOS = new DataOutputStream(socket.getOutputStream());
} catch (IOException e) {
System.out.println(socket + "断开连接");
}
}
void SendFileNames() {
try {
DOS.writeInt(lst.length); //先给客户端写文件夹内文件数目
for(int i=0;i<lst.length;i++) { //客户端也要按顺序接受
DOS.writeUTF(lst[i]); //再依次给客户端写文件名
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() { //线程就有run
SendFileNames();
while(true) {
try {
String name = null;
name = DIS.readUTF(); //读取客户端发送的文件名
obj = new File(SourceFolder,name);
if(!obj.exists()) {
System.out.println("文件不存在");
DOS.writeBoolean(false);//如果文件不存在,给客户端写0
continue;
}
else {
DOS.writeBoolean(true); //如果文件存在,给客户端写1
}
FIS = new FileInputStream(obj);
int n = 0;
byte buf[] = new byte[10000];
while((n = FIS.read(buf)) != -1) {
DOS.writeInt(n); //给客户端写n
DOS.write(buf,0,n); //给客户端写buf数组
DIS.readInt(); //为防止文件过小而加入的服务器客户端应答机制
}
DOS.writeInt(n); //最后服务器再给客户端写入一次n,这时n为-1
FIS.close();
System.out.println("已完成端口为"+socket.getPort()+"客户端的一次复制操作");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
void AcceptClient() {
while(true) { //循环
try {
Socket socket = null;
socket = sSocket.accept(); //等待客户端连接
System.out.println("客户端成功连接,端口为: " + socket.getPort());
new ClientThread(socket).start(); //把socket作为参数传入构造函数,再start
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new TFileCopyServer().AcceptClient();
}

}

三角形计算客户端界面

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
public class TTriangleClientFrame extends JFrame{

JTextArea Area; //文本区域的应用
Socket socket = null;
DataInputStream DIS = null;
DataOutputStream DOS = null;
int Connectable = 0;//用于控制按钮可用不可用
public TTriangleClientFrame() {
Init();
AddFunction();
setSize(550,450);
setLocationRelativeTo(null);
setTitle("客户端");
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
void Init() {
setLayout(new BorderLayout());

JPanel North = new JPanel();
North.setLayout(new BorderLayout());

JPanel CenterPanel = new JPanel();
CenterPanel.setLayout(new FlowLayout());
L1 = new JLabel("SideA");
T1 = new JTextField(10);
L2 = new JLabel("SideB");
T2 = new JTextField(10);
L3 = new JLabel("SideC");
T3 = new JTextField(10);
B2 = new JButton("Send");
CenterPanel.add(L1);
CenterPanel.add(T1);
CenterPanel.add(L2);
CenterPanel.add(T2);
CenterPanel.add(L3);
CenterPanel.add(T3);
CenterPanel.add(B2);

B1 = new JButton("连接到服务器");
North.add(B1,BorderLayout.NORTH);
North.add(CenterPanel,BorderLayout.CENTER);

Area = new JTextArea(); //文本区域加滑动条的处理方法
JScrollPane Center = new JScrollPane(Area); //把区域当做参数传进来

add(North,BorderLayout.NORTH);
add(Center,BorderLayout.CENTER);

B2.setEnabled(false); //设置按钮不可用
}

void AddFunction() { //用于添加功能
B1.addActionListener(new ActionListener() { //匿名类
public void actionPerformed(ActionEvent e) {
if(Connectable == 0) {
try {
InetSocketAddress ISA = new InetSocketAddress("127.0.0.1",2018);
socket = new Socket();
socket.connect(ISA); //文本区域加文本函数append()
Area.append("服务器连接成功,当前端口地址: " +
socket.getLocalSocketAddress() + '\n');
try {
DIS = new DataInputStream(socket.getInputStream());
DOS = new DataOutputStream(socket.getOutputStream());
} catch (IOException e1) {
e1.printStackTrace();
}
} catch (IOException e1) {
e1.printStackTrace();
}
Connectable = 1;
B1.setEnabled(false);
B2.setEnabled(true);
}
}
});
B2.addActionListener(new ActionListener() { //匿名类
public void actionPerformed(ActionEvent e) {
Double a = Double.parseDouble(T1.getText()); //把字符串转Double
Double b = Double.parseDouble(T2.getText()); //转int同理,parseInt即可
Double c = Double.parseDouble(T3.getText());
try {
DOS.writeDouble(a); //给服务器发送数据
DOS.writeDouble(b);
DOS.writeDouble(c);
Area.append(DIS.readUTF() + '\n'); //从服务器接受数据
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
}

public static void main(String[] args) {
new TTriangleClientFrame();
}
}

UDP聊天软件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
public class TUDPAorB {

public static void main(String[] args) {
SendThread_A ST = new SendThread_A();
ReceiveThread_A RT = new ReceiveThread_A();
ST.start(); //启动发送和接收线程
RT.start();
System.out.println("A已启动");
}

}
class SendThread_A extends Thread{ //发送线程
DatagramSocket sendS = null; //UDP用DatagramSocket
InetSocketAddress sa = null; //ISA指定IP和端口
public SendThread_A(){
super();
try {
sendS = new DatagramSocket();
sa = new InetSocketAddress("127.0.0.1",8888);
} catch (SocketException e) {
e.printStackTrace();
}
}
public void run() { //建立DatagramPacket然后用DatagramSocket的send即可
while(true) { //循环
try {
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();
byte []data = str.getBytes(); //字符串转字节数组
DatagramPacket outP = new DatagramPacket(data,data.length,sa);
sendS.send(outP); //DatagramPacket构造函数 ↑
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class ReceiveThread_A extends Thread{ //接收线程
DatagramSocket receiveS = null; //DatagramSocket
public ReceiveThread_A() {
super();
try {
receiveS = new DatagramSocket(8889); //端口别重了
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void run() { //建立DatagramPacket然后用DatagramSocket的receive即可
while(true) {
try {
byte []buf = new byte[100];
DatagramPacket inP = new DatagramPacket(buf, 100);
receiveS.receive(inP);
String data = new String(buf,0,inP.getLength()); //确定长度
if(data.equals("TIME")) {
System.out.println(new Date().toString());
continue;
}
else {
System.out.println("B: " + data);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

考后总结

本来想“得救之道,就在其中”的,结果失败了失败了失败了失败了失败了失败了失败了失败了失败了失败了失败了失败了失败了失败了失败了失败了失败了失败了失败了失败了失败了失败了失败了失败了失败了失败了失败了失败了失败了失败了失败了失败了

令人感叹,多线程服务器客户端交互没能完全实现,考前没有着重复习

不过就花了一晚上看Java,平时学得挺好来着,没花多久时间复习Java,算是给考试周节约了不少时间

不过幸亏没能“得救之道,就在其中”,书上对象流输入输出讲的比自己写的更详细,因祸得福了