?? 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 + -