Java线程可以执行不同的任务?
我正在看一个示例代码,
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());
}
}
和
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.示例的链接是: http://www. cs.nccu.edu.tw/~linw/javadoc/tutorial/java/threads/simple.html
P.S. Example's link is: http://www.cs.nccu.edu.tw/~linw/javadoc/tutorial/java/threads/simple.html
SimpleThread
的每个实例都有其自己的本地类存储.只要您不使用标记为static
的字段,每个线程都将执行自己的代码".在线程之间同步值在 上要困难得多.
Each instance of SimpleThread
has it's own local class storage. As long as you aren't using fields marked as static
, then each thread will "do its own code". It is much harder to synchronize values between threads.
例如:
class SimpleThread extends Thread {
// this is local to an _instance_ of SimpleThread
private long sleepTotal;
public SimpleThread(String str) {
super(str);
}
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(i + " " + getName());
try {
long toSleep = Math.random() * 1000;
// add it to our per-thread local total
sleepTotal += toSleep;
sleep(toSleep);
} catch (InterruptedException e) {}
}
System.out.println("DONE! " + getName());
}
}