class SalesPersons implements Runnable{
String[] names ={"Shubham","Shreyanshi","Sanjay","Sujeet","Utsab"};
public void run(){
for(int loop=0;loop<names.length();loop++){
syso(names[loop]);
}
}
}
class Days implements Runnable{
String[] days ={"Sat","Sun","Mon","Tue","Wed","Thu","Fri"};
public void run(){
SalesPersons sp_obj = new SalesPersons();
Thread t2 = new Thread(sp_obj,"sales_persons");
t2.start();
for(int loop=0;loop<days.length();loop++){
if(days[loop].equalsIgnoreCase("Sun"))
t2.suspend();
if(days[loop].equalsIgnoreCase("Wed"))
t2.resume();
syso(days[loop]);
}
}
public static void main(String args[]){
Days day_obj = new Days();
Thread t1 = new Thread(day_obj,"days");
t1.start();
}
}
Desired output:
Sat <--|---Thread randomness but as per syso order
Shubham <--|
Sun <--|
Mon |---Fixed order
Tue <--|
Wed <--|
Shreyanshi |
Sanjay |
Thu |---Thread randomness but as per syso order
Fri |
Sujeet |
Utsab <--|
Sometimes I am getting:
Sample:1
Sat
Sun
Sample:2
Sat
Shubham
Sample:3
Sat
Shubham
Sun
Sample:4
Sat
Sample:5
Sat
Sun
Mon
Tue
Wed
为什么?考虑到打印的随机性,应该打印12行,因为线程相互竞争。但是每次太阳照应该按照确切的顺序打印。我无法理解为什么我会在上面的示例输出中得到不需要的输出。