📄 pressuretest.java~25~
字号:
package pressuretest;import java.util.*;import cartinterface.*;import data.*;public class PressureTest { //创建记录线程生成变量 int threadNum = 0; //创建线程的总数变量 int totalThread = 20; //创建记录线程总运行时间变量 long eachThreadCostTimes = 0; //创建记录线程成功完成运行变量 int threadSuccessDone = 0; //创建记录线程运行失败变量 int threadFailureDone = 0; public static void main(String[] args) { new PressureTest(); } public PressureTest(){ //创建等待类 Object wait = new Object(); //创建一个线程数组 Thread1[] thread1s = new Thread1[totalThread]; //创建线程 for(int i = 0; i < totalThread; i++ ){ thread1s[i] = new Thread1(String.valueOf(i), wait, this); thread1s[i].start(); } while(true){ //停止运行半秒钟 try { Thread.sleep(500); } catch (Exception ex) {} if(threadNum == totalThread){ synchronized (wait) { //使所有线程同时运行 wait.notifyAll(); } break; } } } //每个线程完成运行后运行的方法 public void threadDone(long eachThreadCostTime, boolean success){ //增加线程完成数 if(success){ threadSuccessDone++; }else{ threadFailureDone++; } eachThreadCostTimes += eachThreadCostTime; if((threadSuccessDone + threadFailureDone) == totalThread){ System.out.println("线程运行的平均时间是" + eachThreadCostTimes/totalThread); System.out.println("总线程数是" + totalThread + " 成功运行数是" + threadSuccessDone + " 失败运行数是" + threadFailureDone); } } 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();} catch (Exception ex) {} } //取得线程开始运行的时间 long startTime = System.currentTimeMillis(); //创建商品窗口类 CartFrame categoryFrame = new CartFrame(new Cart()); //创建购物车窗口类 CartViewFrame productFrame = new CartViewFrame(new Cart()); //取得线程结束的时间 long endTime = System.currentTimeMillis(); //清空窗口类 categoryFrame = null; productFrame = null; //计算线程的运行时间 long eachThreadCostTime = endTime - startTime; if(true){ System.out.println("线程" + this.name + "通过检验. 运行时间是" + eachThreadCostTime + "微秒."); //将线程运行的时间传回主类 pressTest.threadDone(eachThreadCostTime,true); }else{ System.err.println("线程" + this.name + "不通过检验. 运行时间是" + eachThreadCostTime + "微秒."); //将线程运行的时间传回主类 pressTest.threadDone(eachThreadCostTime,false); } }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -