I am looking at an example which code is:
class SimpleThread extends Thread {
public SimpleThread(String str) {
super(str);
}
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(i + " " + getName());
try {
sleep((int)(Math.random() * 1000));
} catch (InterruptedException e) {}
}
System.out.println("DONE! " + getName());
}
}
and
class TwoThreadsTest {
public static void main (String args[]) {
new SimpleThread("Jamaica").start();
new SimpleThread("Fiji").start();
}
}
My question is: is there a way each thread does its own code? For example, one thread increments a variable, while the other thread increments other variable.
Thanks.
P.S. Example’s link is: http://www.cs.nccu.edu.tw/~linw/javadoc/tutorial/java/threads/simple.html
Each instance of
SimpleThreadhas it’s own local class storage. As long as you aren’t using fields marked asstatic, then each thread will “do its own code”. It is much harder to synchronize values between threads.For example: