2012-07-31 2 views
0

아래 코드에서 thread.join을 사용하는 데 문제가 있습니다. 그 다음에 코드를 실행하기 전에 스레드가 완료 될 때까지 기다려야합니다. 그것은 다른 상황에서 다르게 행동했습니다. 내 코드가 잘 어울리는 경우android multithreading : thread.join()이 예상대로 작동하지 않습니다.

내가 확인하는 세 가지 사례를 가지고

    응용 프로그램은 처음 사용
  • - 두 번째를 사용 예상대로 작동하지만
  • 앱을 다운로드하는 동안로드 페이지가 표시되지 않습니다 시간 (DB가 최신) - 내가 생각 화면 블랙 아웃 후 충돌,

를 업데이트하지 않습니다 -

  • 앱은 (데시벨은, 오래된 업데이트해야합니다) 세 번째 시간을 사용
  • 괜찮 작동 티 문제 onCreate 방법에의 코드 :

    로그를 기반으로
    dropOldSchedule(); 
    dropThread.join(); 
    triggerDownload(); 
    

    코드는 문제가 될 수있는 것 ...이 부분 이전까지 작동?


    MainActivity.java

    public class MainActivity extends Activity { 
    
    final static int INDEX_ACCTTYPE = 0; 
    final static int INDEX_ECN = 1; 
    final static int INDEX_TLN = 2; 
    final static int INDEX_SIN = 3; 
    final static int INDEX_MOBILE = 4; 
    final static int INDEX_CITY = 5; 
    final static int INDEX_START_DATE = 6; 
    final static int INDEX_START_TIME = 7; 
    final static int INDEX_END_DATE = 8; 
    final static int INDEX_END_TIME = 9; 
    final static int INDEX_REASON = 10; 
    final static int INDEX_DETAILS = 11; 
    
    DatabaseHandler db; 
    String str; 
    ProgressDialog pd; 
    
    TextView homeText1, homeText2, homeText3, homeText4; 
    
    final private String csvFile = "http://www.meralco.com.ph/pdf/pms/pms_test.csv"; 
    final private String uploadDateFile = "http://www.meralco.com.ph/pdf/pms/UploadDate_test.txt"; 
    
    Thread dropThread = new Thread(new Runnable() { 
    
        public void run() { 
         db = new DatabaseHandler(MainActivity.this); 
         db.dropOldSchedule(); 
    
         runOnUiThread(new Runnable() { 
          public void run() { 
           while (!pd.isShowing()); 
           db.close(); 
           pd.dismiss(); 
          } 
         }); 
        } 
    
    }); 
    Thread getUploadDateThread = new Thread(new Runnable() { 
    
        public void run() { 
    
         try { 
          URL myURL = new URL(uploadDateFile); 
    
          BufferedReader so = new BufferedReader(new InputStreamReader(myURL.openStream())); 
          while (true) { 
           String output = so.readLine(); 
           if (output != null) { 
            str = output; 
           } 
           else { 
            break; 
           } 
          } 
         so.close(); 
         } 
         catch (MalformedURLException e) { 
          e.printStackTrace(); 
         } catch (IOException e) { 
          e.printStackTrace(); 
         } 
    
         runOnUiThread(new Runnable() { 
          public void run() { 
           while (!pd.isShowing()); 
           pd.dismiss(); 
          } 
         }); 
        } 
    
        }); 
    Thread downloadThread = new Thread(new Runnable() { 
    
        public void run() { 
    
         db = new DatabaseHandler(MainActivity.this); 
         db.beginTransaction(); 
    
         try { 
          URL url = new URL(csvFile); 
    
          Log.i("dl", "start"); 
    
          InputStream input = url.openStream(); 
          CSVReader reader = new CSVReader(new InputStreamReader(input)); 
          Log.i("dl", "after reading"); 
    
          String [] sched; 
          while ((sched = reader.readNext()) != null) { 
           if(sched[INDEX_CITY].equals("")) sched[INDEX_CITY]="OTHERS"; 
           try { 
    
            db.addRow(sched[INDEX_SIN], sched[INDEX_CITY], 
              sched[INDEX_START_DATE], sched[INDEX_START_TIME], 
              sched[INDEX_END_DATE], sched[INDEX_END_TIME], 
              sched[INDEX_DETAILS], sched[INDEX_REASON]); 
           } catch (IndexOutOfBoundsException e) { 
            db.addRow(sched[INDEX_SIN], sched[INDEX_CITY], 
              sched[INDEX_START_DATE], sched[INDEX_START_TIME], 
              sched[INDEX_END_DATE], sched[INDEX_END_TIME], 
              "", sched[INDEX_REASON]); 
            //e.printStackTrace(); 
           } 
          } 
          input.close(); 
          Log.i("dl", "finished"); 
    
         } catch (MalformedURLException e) { 
          e.printStackTrace(); 
          db.endTransaction(); 
         } catch (IOException e) { 
          e.printStackTrace(); 
          db.endTransaction(); 
         } 
         Log.d("Count", ""+db.count()); 
         db.setTransactionSuccessful(); 
         db.endTransaction(); 
    
         writeUploadDateInTextFile(); 
    
        } 
    
    }); 
    
    @SuppressWarnings("unqualified-field-access") 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.pms_main); 
    
        Button home = (Button) findViewById(R.id.home); 
        home.setOnClickListener(new OnClickListener() { 
    
         @Override 
         public void onClick(View v) { 
          Intent intent = new Intent(MainActivity.this, MeralcoSuite_TabletActivity.class); 
          intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
          startActivity(intent); 
    
          finish(); 
         } 
        }); 
    
        homeText1 = (TextView) findViewById(R.id.home_text1); 
        homeText2 = (TextView) findViewById(R.id.home_text2); 
        homeText3 = (TextView) findViewById(R.id.home_text3); 
        homeText4 = (TextView) findViewById(R.id.home_text4); 
    
        homeText1.setVisibility(View.INVISIBLE); 
        homeText2.setVisibility(View.INVISIBLE); 
        homeText3.setVisibility(View.INVISIBLE); 
        homeText4.setVisibility(View.INVISIBLE); 
    
        getUploadDate(); 
        try { 
         getUploadDateThread.join();  //wait for upload date 
    
         Log.d("getUploadDate","thread died, upload date=" + str); 
    
         if(dbExists()){ 
          db = new DatabaseHandler(MainActivity.this); 
          Log.d("Count", "" + db.count()); 
          db.close(); 
    
          if(!uploadDateEqualsDateInFile()){ 
           dropOldSchedule(); 
            dropThread.join(); 
           triggerDownload(); 
          } 
          showDisclaimer(); 
          Log.i("oncreate", "finished!"); 
          return; 
         } 
    
         triggerDownload(); 
         showDisclaimer(); 
         Log.i("oncreate", "finished!"); 
    
        } catch (InterruptedException e) { 
         // TODO Auto-generated catch block 
         e.printStackTrace(); 
        } 
    
    } 
    
    public void dropOldSchedule(){ 
    
        if(pd!=null && pd.isShowing()) 
         pd.setTitle("Getting upload date..."); 
        else 
         pd = ProgressDialog.show(this, "Getting upload date", 
          "This may take a few minutes...", true, false); 
    
    
        dropThread.start(); 
    } 
    public void triggerDownload() { 
    
        if (!checkInternet()) { 
         showAlert("An internet connection is required to perform an update, please check that you are connected to the internet"); 
         return; 
        } 
    
        if(pd!=null && pd.isShowing()) 
         pd.setTitle("Getting upload date..."); 
        else 
         pd = ProgressDialog.show(this, "Getting upload date", 
          "This may take a few minutes...", true, false); 
    
        downloadThread.start(); 
    
    } 
    
    public void getUploadDate() { 
    
        Log.d("getUploadDate", "getting upload date of schedule"); 
    
        if(pd!=null && pd.isShowing()) 
         pd.setTitle("Getting upload date..."); 
        else 
         pd = ProgressDialog.show(this, "Getting upload date", 
          "This may take a few minutes...", true, false); 
    
    
        getUploadDateThread.start(); 
    
    } 
    
    public void writeUploadDateInTextFile() { 
        Log.d("writeUploadDateTextFile", "writing:"+str); 
    
        try { 
         OutputStreamWriter out = new OutputStreamWriter(openFileOutput(
           "update.txt", 0)); 
         out.write(str); 
         out.close(); 
        } catch (java.io.IOException e) { 
         e.printStackTrace(); 
        } 
    } 
    
    public void showDisclaimer() { 
        Log.d("ShowDisclaimer", "showing disclaimer"); 
    
        homeText3 
        .setText("..." + str 
          + "..."); 
    
    
        homeText1.setVisibility(View.VISIBLE); 
        homeText2.setVisibility(View.VISIBLE); 
        homeText3.setVisibility(View.VISIBLE); 
        homeText4.setVisibility(View.VISIBLE); 
    
        Log.d("showDisclaimer", "finished showing disclaimer"); 
    
    } 
    
    public boolean uploadDateEqualsDateInFile() { 
        Log.d("uploadDateEqualsDateInFile","comparing schedule upload dates"); 
    
        try { 
          String recordedDate = ""; 
          InputStream instream = openFileInput("update.txt"); 
          if (instream != null) { // if file the available for reading 
           Log.d("uploadDateEqualsDateInFile","update.txt found!"); 
    
           InputStreamReader inputreader = new InputStreamReader(instream); 
           BufferedReader buffreader = new BufferedReader(inputreader); 
    
           String line = null; 
           while ((line = buffreader.readLine()) != null) { 
            recordedDate = line; 
            Log.d("uploadDateEqualsDateInFile","recorded:"+recordedDate); 
           } 
    
           Log.d("uploadDateEqualsDateInFile","last upload date: " + str + ", recorded:" +recordedDate); 
    
           if(str.equals(recordedDate)) return true; 
           return false; 
          } 
          Log.d("uploadDateEqualsDateInFile","update.txt is null!"); 
          return false; 
    
        } catch (FileNotFoundException e) { 
         e.printStackTrace(); 
         return false; 
        } catch (IOException e) { 
         e.printStackTrace(); 
         return false; 
        } 
    } 
    
    public boolean checkInternet() { 
        ConnectivityManager cm = (ConnectivityManager) this 
          .getSystemService(Context.CONNECTIVITY_SERVICE); 
    
        NetworkInfo infos[] = cm.getAllNetworkInfo(); 
    
        for (NetworkInfo info : infos) 
         if (info.getState() == NetworkInfo.State.CONNECTED 
           || info.getState() == NetworkInfo.State.CONNECTING) { 
          return true; 
         } 
    
        return false; 
    } 
    
    public boolean dbExists() { 
    
        File database=getApplicationContext().getDatabasePath(DatabaseHandler.DATABASE_NAME); 
    
        if (!database.exists()) { 
         Log.i("Database", "Not Found"); 
         return false; 
        } 
    
        Log.i("Database", "Found"); 
        return true; 
    
    } 
    
    @Override 
    protected void onDestroy() { 
        super.onDestroy(); 
        if (db != null) { 
         db.close(); 
        } 
    } 
    @Override 
    protected void onPause() { 
        super.onPause(); 
        if (db != null) { 
         db.close(); 
        } 
    } 
    

    }

    난 당신의 코드에서 실수 나 문제를 찾을 수 없습니다하지만
    +0

    당신은 AsyncTask를에이 모든 것을 할 수없는 어떤 이유? – Jimmy

    +0

    전체 코드를 여기에 게시하는 것은 좋지 않습니다. –

    +0

    @ James.Elsey, 나는 그것에 대해 연구 중입니다. 그러나이 코드의 문제점이 무엇인지 알고 싶습니다. Andro, 다음에 시도하지는 않겠지 만 볼 수 있다면 쉽게 될 것이라고 생각했습니다. 코드 ... 나는 그것이 어디에 잘못되었는지 잘 모르겠다. – yojoannn

    답변

    2

    죄송합니다. 하지만 다른 스레드에서 뭔가를하기 위해 AsyncTask를 사용하는 것이 좋습니다. AsyncTask는 사용하기가 쉽고 자바의 가장 큰 장점 중 하나라고 말할 수 있습니다. 나는 obj-c에서 그것을 정말로 놓친다.

    http://labs.makemachine.net/2010/05/android-asynctask-example/

    http://marakana.com/s/video_tutorial_android_application_development_asynctask_preferences_and_options_menu,257/index.html

    검사는 이러한 링크는 당신을 도움이되기를 바랍니다.

    1

    이미 AsyncTask이 더 나은 대안이라고 언급했습니다. 그러나 가입 요청 전화가 InterruptedException이 될 수 있습니다. 이처럼 사용해보십시오 :를 Thread.join의

    while(getUploadDateThread.isRunning()){ 
        try{ 
         getUploadDateThread.join(); 
        } catch (InterruptedException ie){} 
    } 
    // code after join 
    
    -1

    요점은 모든 프로세스가 어느 스레드에서 당신이 당신의 현재 실행을 계속하기 전에 완료에 가입했는지 확인하는 것입니다.

    프로그램을 막 막 끝내고 저장이 끝나기 전에 저장을하고 싶다면 실제로 의미가 있습니다. 스레드를 사용 중입니다. onCreate에 참여하면 그 의미에서 도움이되지 않습니다.

    죄송 합니다만, 의심의 여지가 없지만 thread.join이 사용되는 이유를 알고 있는지 확인합니다.

    +0

    커뮤니티 가이드 라인에 따라 위 의견을 의견으로 게시 할 수 있습니다. 대답은 대답 섹션에 게시해야합니다. – Hemanth

    0

    onCreate() 메서드에서 조인을 호출 할 때 UI 스레드를 차단하고 있다는 문제가 있다고 생각합니다. 이 코드를 백그라운드에서 실행해야하는 다른 스레드로 이동시켜야합니다. 그러면 UI를 업데이트 할 수 있습니다.여기

    은 샘플 코드입니다 :

    final Thread t1 = new Thread(); 
        final Thread t2 = new Thread(); 
        t1.start(); 
        t2.start(); 
        new Thread(new Runnable() { 
    
         @Override 
         public void run() { 
          // Perform all your thread joins here. 
          try { 
           t1.join(); 
           t2.join(); 
          } catch (Exception e) { 
           // TODO: handle exception 
          } 
    
    
          // This thread wont move forward unless all your threads 
          // mentioned above are executed or timed out. 
          // ------ Update UI using this method 
          runOnUiThread(new Runnable() { 
    
           @Override 
           public void run() { 
            // Update UI code goes here 
    
           } 
          }); 
    
         } 
        }).start(); 
    
    관련 문제