'How to get all the threads working even when we create a new one in the for loop?
Following code executes but I want it to print a new String tmp of the same length as sample's length.
class T10 {
static String tmp = "", sample = "Manipulate";
public static void main(String args[]) {
for(int i=0;i<sample.length();i++)
new Thread10(i).t.start();
System.out.println(tmp);
}
}
class Thread10 implements Runnable {
int i;
Thread t;
Thread10(int i) {
t = new Thread(this, "Manipulator Thread : "+i);
this.i = i;
}
public void run() {
T10.tmp+=T10.sample.charAt(i);
}
}
Here are some sample outputs:
Mnla
Maniplua
Mpia
Miap
Mu
Solution 1:[1]
Please tell us what output you expect from your code.
Generally spoken:
With your implementation you do start 10 threads (because your sample string has 10 letters). But you have absolutely no control over the order in which the threads are executed and the state of the tmp variable at this time.
This could cause mixed order of letter and letters overwriting one another (like seen in your output).
Once you specify what output you expect it will be possible to suggest a solution.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
