2012-06-25 51 views
0

這是我的代碼,它處理線程。我在run()中遇到了問題,因此我無法編譯它。如果有人知道如何用DateFormat參數調用方法,請告訴我。如何在Java中使用DateFormat參數調用方法?

import java.text.DateFormat; 
import java.text.ParseException; 
import java.util.Calendar; 
import java.util.Date; 

class Base implements Runnable { 
    static DateFormat format = 
    DateFormat.getDateInstance(DateFormat.MEDIUM); 
    public Date parse(String str) throws ParseException { 
    synchronized (getClass()) { 
     return format.parse(str); 
    } 
    } 

    @Override 
    public void run() { 
/*Date date = new Date(111111); 
DateFormat dateF = DateFormat.getDateInstance(DateFormat.FULL, Locale.US); 
date.getDateInstance(dateF);*/ 
parse("Hello"); 
    } 
} 

class Derived extends Base implements Runnable{ 
    public Date doSomethingAndParse(String str) throws ParseException { 
    synchronized(Base.class) { 
     System.out.println("Derived Class"); 
     return format.parse(str); 
    } 
    } 

    public static void main(String[] args) { 
    Derived d = new Derived(); 
    Thread t = new Thread(d); 
    Thread t2= new Thread (d); 
    t.start(); 
    t2.start(); 

    } 

    @Override 
    public void run() { 

getClass(); 
    try { 
     doSomethingAndParse("1111111111"); 
    } catch (ParseException e) { 
     e.printStackTrace(); 
    } 
System.out.println("Run in Derived Class"); 

    } 
} 
+0

傳遞一個int值給函數,然後你可以根據它切換大小寫 – Satya

+0

welcome to stackoverflow。請嘗試格式化源代碼,使其可讀。 –

+0

99%的發佈代碼與您的問題無關。將你的代碼減少到解釋你的問題的1或2行,我猜*這與將DateFormat對象或格式字符串(不明確)傳遞給方法有關。參見[SSCCE](http://sscce.org)瞭解更多關於我在談論的內容。 – Bohemian

回答

0

爲了避免美國的格式和DE之間的麻煩,我用的SimpleDateFormat在我的例子。除此之外,它是非常代碼:

import java.text.*; 
import java.text.ParseException; 
import java.util.Date; 

class Base implements Runnable { 

    // DateFormat format = DateFormat.getDateInstance (DateFormat.MEDIUM); 
    DateFormat format = new SimpleDateFormat ("YYYY-MM-dd"); 

    public Date parse (String str) throws ParseException { 
     return format.parse (str); 
    } 

    @Override 
    public void run() { 
     try { 
      parse ("Hello"); 
     } catch (ParseException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

class Derived extends Base implements Runnable { 

    public Date doSomethingAndParse (String str) throws ParseException { 
     System.out.println ("Derived Class"); 
     return format.parse (str); 
    } 

    @Override 
    public void run() { 
     try { 
      doSomethingAndParse ("1962-10-08"); 
     } catch (ParseException e) { 
      e.printStackTrace(); 
     } 
     System.out.println ("Run in Derived Class"); 
    } 

    public static void main (String [] args) { 
     Derived d = new Derived(); 
     Thread t1 = new Thread (d); 
     Thread t2 = new Thread (d); 
     t1.start(); 
     t2.start(); 
    } 
} 

我刪除從日期格式格式的「靜態」修飾符,而「同步」部分。查看Dateformat的javadocs - 它不是threadsave,那麼爲什麼你會在不同的線程中使用相同的格式?躲開它!

的Javadoc:

同步

日期格式不同步。建議爲每個線程創建 單獨的格式實例。如果多個線程同時訪問格式 ,則它必須在外部同步。