This document includes the implementation of PriorityThreadQueue and ListManager classes in Java. PriorityThreadQueue class demonstrates how to compare and sort threads based on their priority, while ListManager class shows how to shuffle and swap elements in two lists.
Contribute Materials
Your contribution can guide someone’s learning journey. Share your
documents today.
1.Questions 1. importjava.util.Comparator; importjava.util.ArrayList; importjava.util.List; importjava.util.Collections; importjava.util.Random; publicclassPriorityThreadQueueextendsThreadimplementsRunnable { public voidrun()//implementing the run method for each Thread { System.out.println("Thisis currently the thread with the highest priority" +this.getPriority()); } //Tocomparethepriorityofthe thread to neccesiate the storage //ofonewiththehighestpriority. static classThreadSortingimplementsComparator<PriorityThreadQueue> { @Override publicintcompare(PriorityThreadQueue t1,PriorityThreadQueue t2) { if(t1.getPriority()>t2.getPriority()) return1; elseif(t1.getPriority() == t2.getPriority()) return0; else return-1; } } //Driverprogramtorandomlyassign priorities to threads //Itteststheirpriorities. public staticvoidmain(String[] args) { //Letscreatethethreads PriorityThreadQueuet1=newPriorityThreadQueue(); PriorityThreadQueuet2=newPriorityThreadQueue(); PriorityThreadQueuet3=newPriorityThreadQueue(); Randomrnd=newRandom(); //Letsrandomlygeneratepriorities for the threads //throwsIllegalArgumentexception otherwise t1.setPriority(rnd.nextInt(10)); t2.setPriority(rnd.nextInt(10)); t3.setPriority(rnd.nextInt(10)); List<PriorityThreadQueue>list =newArrayList<>(); list.add(t1); list.add(t2); list.add(t3); Collections.sort(list,newThreadSorting());//sorting the threads based on our //ThreadSortingclass //Testthethreadsstoredin the arraylist for(inti=list.size()-1;i >0;i--) { PriorityThreadQueuecurr = list.get(i); curr.run(); } } }
Secure Best Marks with AI Grader
Need help grading? Try our AI Grader for instant feedback on your assignments.