Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

3. (20 pts) What is changed if the method Thread.yield() is added between lines

ID: 3798985 • Letter: 3

Question

3. (20 pts) What is changed if the method Thread.yield() is added between lines 23 and 24? Explain.

1 public class TaskThreadDemo {
2    public static void main (String args []) {
3    String [] sa = {"a", "X", "+", "."};
4    for (String s: sa) {
5      Runnable ps = new PrintChar (s, 200);
6      Thread ts = new Thread (ps, s);
7      ts.start ();
8    } // end for each character
9    } // end main
10 } // end class TaskThreadDemo
11
12 class PrintChar implements Runnable {
13   String ch;
14   int times;
15
16   public PrintChar (String c, int n) {
17     ch = c;
18     times = n;
19   } // end constructor
20
21   public void run () {
22     for (int i = 0; i < times; i++) {
23       System.out.print (ch);
24     } // end for loop
25   } // end method run
26 } // end class PrintChar

Explanation / Answer

Every Thread have some priority, when we use Thread.yield() then it sent back the current thread to runnable to allow other threads of the same priority to get their chance.

so if you see here by using Thread.yield() and without using Thread.yield() then you realise better.

by using Thread.yield the output is like this(I am not going to write whole output, just I taking 1st line)

aX+aX.a+a.X.a+.Xa+X.aX+Xa.+Xa.+Xa.+aX+a.a+Xa.X+a.X+aX.+aX.+a+.X+a.X+a.X+a

without using Thread.yield the output is like this(here also I taking few line)

aaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaa.............................++++++

CONCLUSION: So the use of Thread.yield() here is to give chance to other equal priority thread.

A yield() won't cause a thread to go to waiting/sleeping/blocking state but at most a yield() will cause a thread to go from running to runnable state to give chance to other.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote