[英]Java threads to do different tasks?
我正在看一个代码是哪个代码:
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();
}
}
我的问题是:每个线程都有自己的代码吗? 例如,一个线程增加一个变量,而另一个线程增加其他变量。 谢谢。
PS示例的链接是: http : //www.cs.nccu.edu.tw/~linw/javadoc/tutorial/java/threads/simple.html
我是Java和线程的新手,但你可以做这样的事情(这可能不是很有效)但是使用if语句来检查线程的id或getName(),如果它.equals特定线程的名称然后这样做等
所以这样的事情:
int i;
int j;
if ("thread 2".equals(Thread.currentThread().getName())){
i++;
System.out.println("this is thread 2");
}
else {
j++;
...
}
这应该允许您使线程在相同的run()方法下运行不同的任务
SimpleThread
每个实例都有自己的本地类存储。 只要您没有使用标记为static
字段,那么每个线程都将“执行自己的代码”。 在线程之间同步值要困难得多。
例如:
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());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.