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>();
- // 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(int _tn) {
- ThreadNumber = _tn;
- }
- // push a matrix top of 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 Matrix Pop(Matrix m) {
- que.remove(m);
- return m;
- }
- // remove the bottom matrix
- public Matrix Pop() {
- Matrix m = Bottom();
- return Pop(m);
- }
- // top matrix in the que
- public Matrix Top() {
- return que.get(que.size() - 1);
- }
- // bottom matrix in the que
- public Matrix Bottom() {
- return que.get(0);
- }
- // if it's finished, the thread loop will stop
- public boolean finished = false;
- public boolean paused = false;
- // called when the thread starts
- @Override
- public void run() {
- // report when the thread started
- if (!test.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) {
- // generate submatrices/calculate results
- if (que.size() > 0) {
- Matrix _t = Bottom();
- _t.run();
- } else {
- // or else wait until this thread has more than 0 elements in
- // the que
- try {
- synchronized (thisThread) {
- paused = true;
- thisThread.wait();
- }
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- // report when the thread finished
- if (!test.quiet) {
- calcTime = System.nanoTime() - starttime;
- System.out.println("Thread " + ThreadNumber + " stopped\nExecution time was " + calcTime + " ns");
- }
- }
- }
Add Comment
Please, Sign In to add comment