- Create a Student class with name, mark1, mark2, mark3 and sum variables.
- Create an ArrayList with 4 student objects with some values.
- Create a MarkEvaluation thread and ShowMark thread.
- MarkEvaluation should perform the calculation of the total marks for each student.
- ShowMark thread should display the calculated sum.
- Use the join method to prevent the ShowMark thread to run before MarkEvaluation.
Its not homework.Part of some practice am doing.Here they asked me to run 2 threads doing different things but I don’t know if we can run 2 run() methods.How can I perform 2 different operations? Sorry am just starting to learn threads.This is what I’ve done but it is incomplete.
import java.util.*;
class Student implements Runnable
{
public Student()
{
List<Object> list = new ArrayList<Object>();
list.add("robin");
list.add("ravi");
list.add("raj");
list.add("sam");
}
String name;
int mark1=30,mark2=45,mark3=70,sum=0;
public void run()
{
sum = mark1+mark2+mark3;
}
}
public class Ch3Lu2Ex3
{
public static void main(String[] args)
{
Student stu = new Student();
Thread MarkEvaluation = new Thread(stu);
MarkEvaluation.start();
Thread ShowMark = new Thread();
}
}
You’re on the right track. What you want to do now is create another
Runnableclass for displaying the resulting sum, and you need to find some way of sharing the calculated sum from theMarkEvaluationthread. I suggest using aBlockingQueue, as thetake()method will block until thesumhas beenputonto the thread, satisfying your last requirement without having to usejoin().Explicitly, you need 2 classes implementing
Runnable, 1 you already have, and another for displaying the result. You need to share aBlockingQueuebetween them, and you need to start both threads by instantiating aThreadand callingstart(). Hopefully this will put you on the right track without simply giving you the code.Alternatively, you could have the
ShowMarkRunnablekeep a reference toStudentas well as the thread used to runStudent(calledMarkEvaluationabove),joinon the thread, and then callgetSum()(or similar) to retrieve the sum fromStudent.