understanding code!!
i have this code and am finding it hard to understand it, i know it will create threads, but does it go a,b,c,a,b,c?
class StringCyclerimplements Runnable
{
private String s;
public StringCycler(String s)
{
this.s = s;
}
privatevoid printChar(int i)
{
System.out.println(this.s.charAt(i));
}
privatevoid cycle()
{
for (int i = 0; i < this.s.length(); i++)
{
this.printChar(i);
}
}
publicvoid run()
{
for (;;)
{
this.cycle();
}
}
}
publicclass Main(String[] args)
{
publicstaticvoid main(String[] args)
{
StringCycler c =new StringCycler("abc");
Thread t1 =new Thread(c);
Thread t2 =new Thread(c);
t1.start();
t2.start();
}
}
Each StringCycler instance will cycle thru a, b, and c over and over again. Since there are 2 threads doing that though, the order of execution is indeterminate. You may get a, b, a, c, b, ... depending on which thread is given CPU cycles at the time. The bolded items are from the 2nd thread for empasis.
> i have this code and am finding it hard to understand> it, i know it will create threads, but does it go> a,b,c,a,b,c?Probably not. ~
> > how could i modify the code so it will only give me> > a,b,c,a,b,c?> > Don't use threads?Indeed. That, or develop some complex means of observation/notification. Don't rely on the thread scheduler for behavior.~
> how could i modify the code so it will only give me> a,b,c,a,b,c?System.out.println("abcabc");Or if you use just one thread from the code you posted, it'll print "abc" over and over again.Message was edited by: paulcw
> > how could i modify the code so it will only give me> > a,b,c,a,b,c?> > System.out.println("abcabc");<cough>commas</cough>;o)~