[英]In Java why we need an object to call a function in the main function of the same class but no object for other function which is not main?
[英]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?
假设我从我的主要创建制作人。 然后,这个生成器创建它自己的线程,当它产生一些东西时调用一个函数main.addProduct()
。 这个函数是否会在调用它的生产者的同一个线程中执行? 或者它将在与main相同的线程中工作,这意味着它将等到所有其他任务完成后再解决它?
为了显示
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();
}
问题是结果是否会成功
I'm ugly
I'm pretty!
I'm pretty!
I'm pretty!
...
要么
I'm pretty!
I'm pretty!
I'm pretty!
I'm ugly
I'm pretty!
I'm pretty!
I'm pretty!
...
线程不关心它们正在运行的对象。 除非它们与另一个线程连接(即它们被停止)或者如果它们遇到生成新线程的代码,所以一切都保留在线程中。
显然,如果从多个线程调用方法,尤其是具有副作用的方法main.addProduct()
如main.addProduct()
,则需要考虑同步。
如果从生产者线程调用main.addProduct()
,那么它就是执行该方法的线程,而不是主线程。 它不会等到主线程中的其他任务完成,因此这里可能存在同步错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.