Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package project;
- import java.util.Vector;
- public class ThreadedMatrix implements Runnable {
- // que of matrices that need to be calculated
- public Vector<Matrix> que = new Vector<Matrix>();
- // do we want to know when each thread starts and stops
- public boolean quiet;
- // which thread this is // an index
- public int ThreadNumber;
- // when this thread started and how long it took to finish
- long starttime, calcTime;
- // reference to the actual thread, necessary for joining/waiting
- public Thread thisThread;
- // array of results from all the processes, will be summed in the main
- // thread
- public static double results[];
- // constructor
- public ThreadedMatrix(boolean _q, int _tn) {
- quiet = _q;
- ThreadNumber = _tn;
- }
- // push a matrix into the que and tell it that it's being calculated by this
- // thread
- public void Push(Matrix m) {
- m.thread = this;
- que.add(m);
- }
- // remove a matrix
- public void Pop(Matrix m) {
- que.remove(m);
- }
- // remove the top matrix. never actually used but added for the heck of it
- public void Pop() {
- que.remove(que.size() - 1);
- }
- // top matrix in the que
- public Matrix Top() {
- return que.get(que.size() - 1);
- }
- // if it's finished, the thread loop will stop
- public boolean finished = false;
- // called when the thread starts
- @Override
- public void run(){
- // report when the thread started
- if (!quiet) {
- starttime = System.nanoTime();
- System.out.println("Thread " + ThreadNumber + " started");
- }
- // every thread is running until every single thread has no more
- // matrices in their ques
- while (!finished) {
- if (que.size() > 0) {
- Matrix _t = Top();
- _t.run();
- if (!quiet) {
- System.out.println(
- "working in thread " + ThreadNumber + ", processes left: " + Matrix.numberOfProcesses
- + "/" + ThreadedMatrix.results.length + ", in que: " + que.size());
- }
- } else {
- try {
- synchronized (thisThread) {
- thisThread.wait();
- }
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- // report when the thread finished
- if (!quiet) {
- calcTime = System.nanoTime() - starttime;
- System.out.println("Thread " + ThreadNumber + " stopped\nExecution time was " + calcTime);
- }
- }
- }
Add Comment
Please, Sign In to add comment