2014-09-18 58 views
1

我是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

回答

1

你應該閱讀一些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(); 

    } 
} 
1

你可以做創建兩個您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

2

您應該擴展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); 
    } 
}