본문 바로가기
코스웨어/10년 스마트폰BSP

[BSP]업무일지-전현수-20100827

by 알 수 없는 사용자 2010. 8. 27.
728x90
반응형

●  스레드 

자바 어플리케이션을 실행시키면 JVM 이 작동하면서 main() 메소드가 수행되는데 그 자체가 하나의 스레드이다. 단일 스레드는 한 프로세스에 하나의 스레드만을 가진 것인데 반해 다중 스래드는  하나의 프로세스에 다수의 스레드를 가지고 동시에 작업을 수행한다. 당연히 하나의 작업을 분할해서 동시에 수행하는 다중 스레드 쪽이 훨씬 성능이 좋다.

스래드를 구현하는 방법은 2가지 이다. 첫 번째 방법은 Thread 클래스를 상속받는 (확장 extends) 방법이고, 두번째 방법은 Runnable 인터페이스를 상속받는 (구현 implements) 방법이다.

스레드를 실행시키기 위해서는 스레드 객체의 start() 메소드를 호출함으로써 실행된다. start() 메소드를 호출하면 run() 메소드가 자동 호출되는데 run() 메소드에는 다중 스레드로 동작시키고자 하는 내용이 기술되어 있다. 그러므로 start() 메소드를 사용하면 자동적으로  스레드가 실행된다.



▶ Thread 클래스 사용법

1. java.lang.Thread 클래스를 상속(처리 로직을 자기고 있는 class) 받아서 처리를 한다.
2. 상속받은 Thread 클래스를 run() 메소드로 오버라이딩해 준다.
3. run() 메소드에 스레드가 일한 작업의 내용을 기술한다.시간이 오래 걸리는 일을 다중 스래드로 구현해야 의미가 있기 떄문에 run() 
   메소드에는 일반적으로 반복문을 기술한다.

제) 스레드1 (1초씩 증가)  스레드2 (3초씩 증가, 일정초가 지나면 정지) 

package Thread;

class ThreadEx extends Thread {
       String name;
       public ThreadEx(String name){
              super(name);  
              this.name=name;
       }

       @Override
       public void run() {
             int i = 0;
             try
            {
                   while(true)
                   {
                          sleep(1000);
                          System.out.println(name+" : "+ ++i +" 초 입니다");
                   }
             }
            catch(Exception e)
            {
                     e.printStackTrace();
            }
       }
}

class ThreadEx1 extends Thread {
        String name;
        boolean isEnd = true;
        public ThreadEx1(String name){
                    super(name);
                    this.name=name;
        } 
 
        @Override
        public void run() {
               int i = 0;
               try
              {
                      while(!Thread.currentThread().interrupted())
                      {
                                 sleep(3000); 
                                 i = i + 2;
                                 System.out.println(name+" : "+ ++i +" 초 입니다");
                      }
              }
              catch(InterruptedException e)
              {
                          e.printStackTrace();
              }
      }
}

   public class ThreadTest{
   
                   public static void main(String[] args) {

                            ThreadEx t1 = new ThreadEx("Thread1");
                            ThreadEx1 t2 = new ThreadEx1("Thread2");   
     
                            t1.start();
                            t2.start();
   
                            try
                            {
                                     Thread.sleep(10000); 
                            }
                           catch(Exception e)
                           {
                                    e.printStackTrace();
                           }
   
                           t2.interrupt();
                           //t2.isEnd = false;  
                }
 }
 


▶ Runnable 인터페이스는 JFrame 나 JApplet 등에서 자바 애니메이션을 구현할 때 사용한다. 즉 이미 다른 클래스를 상속받고 있는
    클래스를 스레드로 구현하고자 할 때는 Thread 클래스를 상속받을 수 없기 때문에 Runnable 인터페이스를 사용하여 구현한다.

    Runnable 인터페이스를 구현하여 스레드 구현 클래스를 정의하고, run() 메소드를 오버라이딩 하여 여기에 스레드로 동작시킬 로직을 
    기술한다.

예제)  점 이미지가 뿌려짐

package Runab2;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.util.Random;
import javax.swing.JFrame;

class GraphicThread extends JFrame implements Runnable
{
         int num;
         Color color;
         Random r;
         int x;
         int y;
 
        public GraphicThread(int n)
        {
               num = n;
               color = Color.red;
               r = new Random();
               setSize(200,200);
               setVisible(true);
               this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }

        public void paint(Graphics g)
        {
              g.setColor(color);
              g.fillOval(x, y, 3, 3);
        }

        public void update(Graphics g)
        {
              g.clipRect(x, y, 3, 3);
              paint(g);
        }
 
        public void run()
        {
              Rectangle rec = getBounds();
              for(int i = 0; i<num; ++i)
              {
                         x = r.nextInt(rec.width);
                         y = r.nextInt(rec.height);
                         repaint();
                         try
                         {
                                  Thread.sleep(100);
                         }
                         catch(Exception e)
                         {
                                  e.printStackTrace();
                         }
              }
         }

         public class Runab2
         {
                   public static void main(String[] args)
                   {
                             GraphicThread gt = new GraphicThread(2000);
                             Thread t = new Thread(gt);
                              t.start();
                   }
         }




● Android List 생성 및 삭제

package ListTest.net;

import java.util.ArrayList;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class ListTest extends Activity {
    
  //변수등록
  ArrayList<String> al; //객체를 저장
  ArrayAdapter<String> Adapter; 
  ListView lv;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //이름(객체) 등록
        al = new ArrayList<String>();
        al.add("김주찬");
        al.add("손아섭");
        al.add("조성환");
    
        //Adapter 만들기
        Adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_single_choice, al);
    
        lv = (ListView)this.findViewById(R.id.ListView01);
        lv.setAdapter(Adapter); //어탭터 붙이기 
        lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        lv.setOnItemClickListener(mSelectItem);
    
        this.findViewById(R.id.Button01).setOnClickListener(mButton);
        this.findViewById(R.id.Button02).setOnClickListener(mButton);
    }
    
    private View.OnClickListener
      mButton = new View.OnClickListener() 
      {
      
        @Override
        public void onClick(View v)
        {
          EditText edit = (EditText)findViewById(R.id.EditText01);
          switch(v.getId())
          {
            case R.id.Button01:
              //추가
              String text = edit.getText().toString();
              edit.setText("");
              al.add(text);
              Adapter.notifyDataSetChanged();
              break;
        
            case R.id.Button02:
              //삭제
              int id;
              id = lv.getCheckedItemPosition();
              if(id != ListView.INVALID_POSITION)
              {
                al.remove(id);
                lv.clearChoices();
                Adapter.notifyDataSetChanged();
              }
              break;
          }
        }
      }; 
      
        private AdapterView.OnItemClickListener
          mSelectItem = new AdapterView.OnItemClickListener()
          { 
   
            @Override    
            public void onItemClick(AdapterView<?> adv, View View, int position, long id)
            {
              String text;
              text = al.get(position);
              Toast.makeText(ListTest.this, text, Toast.LENGTH_SHORT).show();
            }
  
          };
}


728x90