[英]Java need help in threads/ code compiling debugging
Question2: I have almost same question but with Threads here is the code: 问题2:我有几乎相同的问题,但这里的线程是代码:
public class Example5 implements Runnable {
static int a=0;
public Example5() {
a++;
}
public int getA() {
return (a);
}
public void run() {
System.out.println(getA());
}
public static void main(String[] s) {
Example5 ex1 = new Example5();
new Thread(ex1).start();
Example5 ex2 = new Example5();
new Thread (ex2).start();
}
}
it says to me it must print: 1 or 2 2 anyone can explain this in threads. 它告诉我它必须打印:1或2 2任何人都可以在线程中解释这一点。
Also anyone can explain to me what happen when i do for example(Not related to first question) 也有人可以向我解释当我这样做时会发生什么(与第一个问题无关)
Thread t = new Thread();
t.start();
Thread t2 = new Thread();
t2.start();
Do they work sorted, (like first thread works first and then second thread) or it just goes randomly. 他们的工作是否排序,(如第一个线程首先工作,然后是第二个线程)或它只是随机进行。 thanks
谢谢
Example5 ex1 = new Example5(); // a = 1
new Thread(ex1).start(); // start a new thread that will execute independently from current thread
Example5 ex2 = new Example5(); // a = 2 (a is static hence shared)
new Thread (ex2).start(); // start a new thread again
// thread1 and thread2 finish (the order is not determined - could be
// thread2 first, then thread1)
// prints: 2 2
// If Thread1 finishes before the second "new Example5()" completes
// prints: 1 2
For the last question: kind of randomly. 对于最后一个问题:有点随机。 Since there is no synchronisation between your 3 threads (current, spawned thread1, spawn thread2).
由于3个线程(当前,生成的thread1,spawn thread2)之间没有同步。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.