我是学习多线程,我有点困惑的几件事情,多个线程访问方法
例如
public class Example{
public void function1(){
int toPrint = 0;
System.out.println(toPrint);
for(int i = 0; i < 10; i++)
System.out.println("hello stackOverflow!");
}
public syncrhonized void function2(){
...
}
}
public static void main(String[] args) {
Example example = new Example();
for (int i = 0; i < 10; i++) {
RunningThread thread = new RunningThread(example);
thread.start();
}
}
像这样
public class RunningThread{
Example instanceClass;
public RunningThread(Example instanceClass){
this.instanceClass = instanceClass;
public void run(){
while(true){
instanceClass.function1();
instanceClass.function2();
}
}
现在循环我不能显示图像,但我想在我的dubts清楚,所以
如果我开始N个线程,我必须打算这种情况
_______________________________ ______________________________
| thread1 | | thread..N |
................................. ................................
| function1 | | function1 |
| int toPrint = 0; | | int toPrint = 0; |
| System.out.println(toPrint); | | System.out.println(toPrint);|
| for(int i = 0; i < 10; i++) | | for(int i = 0; i < 10; i++) |
| System.out.println(); | | System.out.println(); |
--------------------------------- --------------------------------
什么,我的意思是说,每个线程都有自己的流量(的功能1自己的“副本”),并整理他们将等待执行锁定function2()
后?
或
_______________________________
| thread1 and thread..N |
.................................
| function1 |
| int toPrint = 0; |
| System.out.println(toPrint); |
| for(int i = 0; i < 10; i++) |
| System.out.println(); |
---------------------------------
在这种方式的每个线程shares
相同的功能和内容(因此,例如一个线程初始化值和另一个线程不进行初始化)和精加工后,他们将等待执行锁定的function2()
?
的执行顺序将始终尊重,第一功能1和功能2?
不好意思,如果这么长,反正先谢谢了。
我在代码中看不到任何线程。此外,我没有看到多个线程调用'function2'。 – 2014-11-03 13:12:59
请给我们显示完整的代码。 – TheLostMind 2014-11-03 13:13:32
等待,我会插入当我开始线程,但我认为这是次要的... – user582040 2014-11-03 13:14:29