달력

42025  이전 다음

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

1. Thread 클래스 사용
 public class ThreadTest extends Activity {
    int mMainValue = 0;
    int mBackValue = 0;
   TextView mMainText;
   TextView mBackText;

   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.thread_threadtest);

      mMainText = (TextView)findViewById(R.id.mainvalue);
      mBackText = (TextView)findViewById(R.id.backvalue);
      Button btn = (Button)findViewById(R.id.increase);
      btn.setOnClickListener(new Button.OnClickListener() {
           public void onClick(View v) {
               mMainValue++;
               mMainText.setText("MainValue : " + mMainValue);
              mBackText.setText("BackValue : " + mBackValue);
          }
     });
  
     BackThread thread = new BackThread();
     thread.setDaemon(true);
     thread.start();
 }
 
 class BackThread extends Thread {
     public void run() {
        while (true) {
              mBackValue++;
              //mBackText.setText("BackValue : " + mBackValue);
              try {
                 Thread.sleep(1000);
              } catch (InterruptedException e) { }
        }
     } 

  } // end of main
 } // end of class

2. Runnable 인터페이스 사용
 public class ThreadTest extends Activity {
      int mMainValue = 0;
      int mBackValue = 0;
      TextView mMainText;
      TextView mBackText;

      public void onCreate(Bundle savedInstanceState) {
           super.onCreate(savedInstanceState);
           setContentView(R.layout.thread_threadtest);

           mMainText = (TextView)findViewById(R.id.mainvalue);
           mBackText = (TextView)findViewById(R.id.backvalue);
           Button btn = (Button)findViewById(R.id.increase);
           btn.setOnClickListener(new Button.OnClickListener() {
                 public void onClick(View v) {
                      mMainValue++;
                      mMainText.setText("MainValue : " + mMainValue);
                      mBackText.setText("BackValue : " + mBackValue);
                 }
           });
  
           BackRunnable runnable = new BackRunnable();
           Thread thread = new Thread(runnable);
            thread.setDaemon(true);
            thread.start();
       }
 
      class BackRunnable implements Runnable {
            public void run() {
                  while (true) {
                          mBackValue++;
                          try {
                               Thread.sleep(1000);
                          } catch (InterruptedException e) { }
                  }
            }
       }
 }


Posted by kingjung
|