在Java(Eclipse)中同时运行函数

问题描述:

我是Eclipse和Java的新手,我已经对此进行了相当多的研究,但大多数答案和示例(包括SO)都假定您对于前往哪里有基本的了解,所以请简单地解释(我相信它一定很简单)。在Java(Eclipse)中同时运行函数

我有一个这样的函数,它可以在eclipse中成功运行。不过,我需要能够调用这个函数两次,并让它们同时运行,而不是一个接一个地运行。

public static void reporting(String category, String message) { 
    // Code for this function 
} 

public static void main(String[] args) { 
    // Call the function once 
    reporting("one","Starting"); 

    // Call the function a second time 
    reporting("two","Starting"); 
} 

因此,当前实例1正在运行,然后在第一次完成后执行第二个实例。我需要第一个开始执行,然后第二个直接开始执行。我似懂非懂这个到目前为止是这样的:

public static void main(String[] args) { 
    // Call the function once 
    async reporting("one","Starting"); 

    // Call the function a second time 
    async reporting("two","Starting"); 
} 

然而,这只是抛出约异步不是一个变量,因此显然这是不对的错误。

据我所知,这可能以异步的方式使用异步 - 但正如我所说的无处不在我看起来(所以包括SO 答案)假设你有一个这应该适合的位置的想法。

(PS,我完全离开,我也许要完全错了异步或有可能是更有效的干脆的方式,但任何事情来帮助我学会了正确的方向,有利于)

+0

异步不是Java中的一个关键词。你需要一些运行线程的方式。您可以直接使用Thread来完成它,也可以在线程之上建立各种对并发的支持。 – 2014-09-18 15:39:57

+0

简单的搜索“同时运行两种方法java”就足够了! – Adz 2014-09-18 15:46:05

+0

你到目前为止的答案使用Thread类。对于学习非常基础知识来说不错,但我会看看ExecutorService,因为它提供了更多的功能,并隐藏了多线程应用程序的一些复杂性。 – TedTrippin 2014-09-18 15:56:35

你应该阅读一些Thread tutorials

之一多种可能性:

public static void main(String[] args) 
{ 
    try{ 

    Thread t1 = new Thread() 
    { 
     public void run() { 
      reporting("one","Starting"); 
     }; 

    }; 


    Thread t2 = new Thread() 
    { 
     public void run() { 
      reporting("two","Starting"); 
     }; 

    }; 


    t1.start();//start the threads 
    t2.start(); 

    t1.join();//wait for the threads to terminate 
    t2.join(); 

    }catch(Exception e) 
    { 
     e.printStackTrace(); 

    } 
} 

你可以做创建两个您main()Thread对象是这样的:

Thread thread1 = new Thread() { 
    public void run() { 
     reporting("one","Starting"); 
    } 
}; 

Thread thread2 = new Thread() { 
    public void run() { 
     reporting("two","Starting"); 
    } 
}; 

然后启动2个线程,如:

thread1.start(); 
thread2.start(); 

阅读更多回合Thread Class,也检查出一些useful examples

您应该扩展Thread或实现Runnable。 然后执行run方法中的代码,并通过调用start方法启动Runnables

自成体系,快速和肮脏的例子(主类中):

public static void main(String[] args) throws Exception { 
    // these are spawned as new threads, 
    // therefore there is no guarantee the first one runs before the second one 
    // (although in this specific case it's likely the first one terminates first) 
    new Reporter("one","Starting").start(); 
    new Reporter("two","Starting").start(); 
} 

static class Reporter extends Thread { 
    String category, message; 

    Reporter(String category, String message) { 
     this.category = category; 
     this.message = message; 
    } 
    @Override 
    public void run() { 
     reporting(category, message); 
    } 

    void reporting(String category, String message) { 
     System.out.printf("Category: %s, Message: %s%n", category, message); 
    } 
}