简体   繁体   English

使用线程调用不同的方法

[英]calling different methods using threads

I want to invoke different methods of class at same time. 我想同时调用不同的类方法。

I am creating 2 classes: Main- this instantiate object of Function and Function; 我正在创建2个类:Main-Function和Function的该实例化对象; this extends thread and has 2 methods. 这扩展了线程并具有2个方法。

Main.java Main.java

package ok;
public class Main {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        System.out.println("Welcome to Threading");
        Function f1 = new Function();
        f1.start();
        f1.calling();
        f1.calling2();
    }
}

Function.java Function.java

package ok;

public class Function extends Thread {

    public void run() {
        // TODO Auto-generated method stub
        System.out.println("Run");
        for(int y=140;y<170;y++){
            System.out.println(y);
        }
    }

    synchronized void calling(){
        System.out.println("Let the game begin");
        for(int y=40;y<70;y++) {
            System.out.println(y);
        }
    }

    synchronized void calling2(){
        System.out.println("Let the game begin for me");
        for(int y=0;y<40;y++) {
            System.out.println(y);
        }
    }
}

How can I make the methods calling() and calling2() work at the same time? 如何使calling()calling2()工作? If I start a thread it goes to run() call and doesn't have any return type. 如果我启动一个线程,它将转到run()调用,并且没有任何返回类型。 In my program, I need to have return value as a HashMap . 在我的程序中,我需要具有作为HashMap返回值。

Do I need to create two classes which extends Threads and write logic of calling() , calling2() in run of those two classes? 我是否需要创建两个扩展线程的类并在这两个类的运行中编写calling()calling2()逻辑?

Please suggest. 请提出建议。

Your calling and calling2 methods are synchronized . 您的callingcalling2方法是同步的 The very essence of synchronized keyword is to prevent methods from executing concurrently. synchronized关键字的本质是防止方法并发执行。 So in order to invoke both calling and calling2 in parallel you need to drop the synchronized keyword, at least from the method level. 因此,为了同时调用callingcalling2并行您需要删除synchronized关键字,至少从方法层面。

Then, to invoke two methods at the same time, one Thread object is enough - one invocation can be executed in new thread, the other in the "current" thread, like this: 然后,要同时调用两个方法,一个Thread对象就足够了-一个调用可以在新线程中执行,另一个调用可以在“当前”线程中执行,如下所示:

Thread thread = new MyThread();
thread.start(); // body of run() invoked in a new thread
thread.run();   // body of run() invoked in this thread, concurrently

It's better practice to produce separate Runnable objects for such use-cases, though. 不过,最好为此类用例生成单独的Runnable对象。 This has several advantages over the aformentioned approach: 与上述方法相比,它具有几个优点:

  • it's more flexible - as the action is decoupled from the execution and encapsulated in a separate object, it becomes more like "data". 它更灵活-当操作与执行分离并封装在单独的对象中时,它变得更像“数据”。 If you ever feel the need to change computation strategy - eg use thread pool - it's trivial to do so with Runnable tasks. 如果您感觉需要更改计算策略(例如使用线程池),那么对Runnable任务则很简单。 Not so with Thread extensions. Thread扩展不是这样。

  • it's conceptually more sound, as subclassing a Thread suggests specializing its behaviour, while Runnable s are more like "task containers" - favor composition over inheritance. 从概念上讲,它是更合理的方法,因为对Thread子类化建议专门化其行为,而Runnable则更像是“任务容器”-倾向于组合而不是继承。

  • it's symmetric - no computation is treated differently, it's trivial to change eg which one executes where 它是对称的-不会对计算进行不同的处理,更改很容易,例如哪个执行在哪里

Last, you seem to want to return something from your methods. 最后,您似乎想从您的方法中返回一些东西。 For this, you might use a Future - a java concurrency utility class, representing asynchronous computation. 为此,您可以使用Future-一个Java并发实用程序类,表示异步计算。 In addition to Runnable advantages, it can return a value and offers features like cancellation and state querying. 除了Runnable优点之外,它还可以返回值,并提供取消和状态查询等功能。

You have to have the calls for running the methods inside your run() method. 您必须在run()方法中调用运行这些方法的调用。

Then you can just call the start() method and both methods will run. 然后,您可以只调用start()方法,这两个方法都将运行。 But that does not really solve the problem. 但这并不能真正解决问题。 What you need to do is create two threads and have each of them run their respective threads. 您需要做的是创建两个线程,并使每个线程运行各自的线程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM