[英]If i call a function of my main class in java, from other object which has its own thread, will this function run in separate thread?
Let's say I create Producer from my main. 假设我从我的主要创建制作人。 Then, this producer creates it's own thread, and when it produces something calls a function
main.addProduct()
. 然后,这个生成器创建它自己的线程,当它产生一些东西时调用一个函数
main.addProduct()
。 Will this function execute in the same thread as the producer that called it? 这个函数是否会在调用它的生产者的同一个线程中执行? Or will it work in the same thread as main, meaning it will wait till all the other tasks are finished before solving it?
或者它将在与main相同的线程中工作,这意味着它将等到所有其他任务完成后再解决它?
To illustrate 为了显示
public class MainP{
public static void main(String[] args) {
Producer p1 = new producer;
Producer p2 = new producer;
Producer p3 = new producer;
p1.start();
p2.start();
p3.start();
System.out.println("I'm ugly");
}
public static void prettyFunction(){
System.out.println("I'm pretty!");
}
}
public class Producer extends Thread{
public void run(){
while(true)
MainP.prettyFunction();
}
And the question is whether the result will be 问题是结果是否会成功
I'm ugly
I'm pretty!
I'm pretty!
I'm pretty!
...
or 要么
I'm pretty!
I'm pretty!
I'm pretty!
I'm ugly
I'm pretty!
I'm pretty!
I'm pretty!
...
Threads don't care in which objects they are running. 线程不关心它们正在运行的对象。 Unless they are joined with another thread (ie they are stopped) or if they run into code that generates a new thread, everything stays in the thread.
除非它们与另一个线程连接(即它们被停止)或者如果它们遇到生成新线程的代码,所以一切都保留在线程中。
Obviously if you call a method from multiple threads, especially methods that has side effects such as main.addProduct()
, you need to think about synchronization. 显然,如果从多个线程调用方法,尤其是具有副作用的方法
main.addProduct()
如main.addProduct()
,则需要考虑同步。
If main.addProduct()
is being called from your producer thread, then it's that thread where the method is being executed, not your main thread. 如果从生产者线程调用
main.addProduct()
,那么它就是执行该方法的线程,而不是主线程。 It will not wait until other tasks in your main thread are complete, so there is a potential for synchronization bugs here. 它不会等到主线程中的其他任务完成,因此这里可能存在同步错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.