📄 pressuretest.java
字号:
package pressureTest;
import data.LoginData;
import java.util.*;
public class PressureTest {
//创建记录线程生成变量
int threadNum = 0;
//创建线程的总数变量
int totalThread = 100;
//创建记录线程总运行时间变量
long eachThreadCostTimes = 0;
//创建记录线程完成运行变量
int threadDone = 0;
public static void main(String args[]) {
new PressureTest();
}
public PressureTest() {
//创建等待类
Object wait = new Object();
//创建一个线程数组
Thread[] threadls = new Thread[totalThread];
//创建线程
for (int i = 0; i < totalThread; i++) {
threadls[i] = new Thread1(String.valueOf(i), wait, this);
threadls[i].start();
} while (true) {
if (threadNum == totalThread) {
synchronized (wait) {
//使所有线程同时运行
wait.notifyAll();
}
//停止运行半秒钟
try {
Thread.sleep(500);
} catch (Exception ex) {
break;
}
}
}
}
//每个线程完成运行后的方法
public void threadDone(long eachThreadCostTime) {
//增加线程完成数
threadDone++;
eachThreadCostTimes += eachThreadCostTime;
if (threadDone == totalThread) {
System.out.println("线程运行的平均时间是" + eachThreadCostTimes / totalThread);
}
}
public void increase() {
threadNum++;
}
}
//通过继承Thread类创建线程
class Thread1 extends Thread {
PressureTest pressTest = null;
Object wait = null;
String name = "";
//线程的构造器
Thread1(String name, Object wait, PressureTest pressTest) {
super(name);
this.name = name;
this.wait = wait;
this.pressTest = pressTest;
}
//线程的运行方法
public void run() {
//记录线程的增加数
pressTest.increase(); ;
//使线程停止运行,等待其他线程完成创建
synchronized (wait) {
try {
wait.wait();
System.out.print("线程等待!");
} catch (Exception ex) {
ex.printStackTrace();
}
}
//取得线程开始运行的时间
long startTime = System.currentTimeMillis();
LoginData loginData = new LoginData();
//设置管理员的用户名,密码和用户类别
String name = "manager";
String password = "password";
int state = 0;
//测试用户,密码是否通过
int actualReturn = loginData.checkUser(name, password, state);
//取得线程结束的时间
long endTime = System.currentTimeMillis();
//计算线程的运行时间
long eachThreadCostTime = endTime - startTime;
if (actualReturn == 0) {
System.out.println("线程" + this.name + "通过检验,运行的时间是" +
eachThreadCostTime + "微秒");
} else {
System.err.println("线程" + this.name + "不能通过检验,运行的时间是" +
eachThreadCostTime + "微秒");
}
//将线程运行的时间传回主类
pressTest.threadDone(eachThreadCostTime);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -