¾È±Ô °øºÎ¹æ

Android > Thread »ç¿ëÇϱâ

µî·ÏÀÏ : 2017-07-06 17:21 Á¶È¸¼ö : 53,048

¾Èµå·ÎÀ̵å´Â ¹é±×¶ó¿îµå¿¡¼­ ½ÇÇàµÇ¾î¾ß ÇÏ´Â ±â´ÉÀ» ¼­ºñ½º¶ó´Â ¾ÖÇø®ÄÉÀÌ¼Ç ±¸¼º¿ä¼Ò·Î Á¤ÀÇÇÕ´Ï´Ù.

ÇÏÁö¸¸ º°µµÀÇ ÇÁ·Î¼¼½º°¡ ¾Æ´Ñ µ¿ÀÏÇÑ ÇÁ·Î¼¼½º ³»¿¡¼­ µ¿½Ã¿¡ ´Ù¸¥ ÀÛ¾÷À» ÇØ¾ß ÇÑ´Ù¸é ¸ÖƼ ½º·¹µå ¹æ½ÄÀ» »ç¿ëÇÒ ¼ö ÀÖ½À´Ï´Ù.

ÇöÀç ¼öÇàµÇ´Â ÀÛ¾÷ ÀÌ¿ÜÀÇ ±â´É¸¦ µ¿½Ã¿¡ ó¸®ÇÏ°íÀÚ ÇÒ ¶§ »õ·Î¿î ½º·¹µå¸¦ ¸¸µé¾î ó¸®ÇÒ ¼ö ÀÖ½À´Ï´Ù.

¾Èµå·ÎÀ̵忡¼­ UI󸮸¦ À§ÇØ »ç¿ëµÇ´Â ±âº» ½º·¹µå´Â '¸ÞÀνº·¹µå'¶ó°í ºÎ¸¨´Ï´Ù.

ÀÌ ¸ÞÀνº·¹µå¿¡¼­ ÀÌ¹Ì UI¸¦ Á¢±ÙÇÏ°í ÀÖÀ¸¹Ç·Î »õ·Î »ý¼ºÇÑ ´Ù¸¥ ½º·¹µå¿¡¼­´Â Çڵ鷯(Handler) °´Ã¼¸¦ ÀÌ¿ëÇؼ­ ¸Þ½ÃÁö¸¦ Àü´Þ

ÇÔÀ¸·Î½á ¸ÞÀνº·¹µå¿¡¼­ ó¸®Çϵµ·Ï ¸¸µé ¼ö ÀÖ½À´Ï´Ù.

1. Thread »ç¿ëÇϱâ

¾Èµå·ÎÀ̵忡¼­´Â Ç¥ÁØ ÀÚ¹ÙÀÇ ½º·¹µå¸¦ ±×´ë·Î »ç¿ëÇÒ ¼ö ÀÖÀ¸¹Ç·Î °¡Àå ´Ü¼øÇÑ ¹æ¹ýÀ» ¾Ë¾Æº¸µµ·Ï ÇÏ°Ú½À´Ï´Ù.

½º·¹µå´Â new ¿¬»êÀÚ¸¦ ÀÌ¿ëÇÏ¿© °´Ã¼¸¦ »ý¼ºÇÑ ÈÄ start()¸Þ¼Òµå¸¦ È£ÃâÇÏ¸é ½ÃÀÛÇÒ ¼ö ÀÖ½À´Ï´Ù.

Thread Ŭ·¡½º¿¡ Á¤ÀÇµÈ »ý¼ºÀÚ´Â Å©°Ô ÆĶó¹ÌÅÍ°¡ ¾ø´Â °æ¿ì¿Í Runnable °´Ã¼¸¦ ÆĶó¹ÌÅÍ·Î °¡Áö´Â µÎ°¡Áö·Î ±¸ºÐÇÒ ¼ö ÀÖ½À´Ï´Ù.
 
	int value = 0;
	
	Thread thread1 = new BackgroundThread();
	thread1.start();


	class BackgroundThread extends Thread {
		public void run() {
			while(running) {
				try {
					Thread.sleep(1000);
					value++;
				} catch(InterruptedException ex) {
					Log.e("SampleJavaThread","Exception in thread.",ex);
				}

			}
		}
	}

BackgroundThread Ŭ·¡½º ³»¿¡¼­ 1Ãʸ¶´Ù value °ªÀ» 1¾¿ ´õÇØÁÖ´Â ½º·¹µå ¿¹Á¦ ÀÔ´Ï´Ù.
 
	Thread background1 = new Thread(new Runnable() {
		public void run() 
		{
			try  {    				 
				//¿©±â¿¡ ÀÛ¾÷ÇÒ ³»¿ëÀ» ³Ö´Â´Ù.
				Thread.sleep(1000);       
				value++;
			} catch (Throwable t) 
			{
				// ¿À·ù°¡ ¹ß»ýÇÏ¸é ¹é±×¶ó¿îµå ½º·¹µå¸¦ ±×´ë·Î Á¾·á.
				Log.e("SampleJavaThread","Exception in thread.",ex);
			}
		}
	});

	background1.start();


ÀÌ µÎ¹ø° ¹æ¹ýÀº Ŭ·¡½º ³»ºÎ¿¡¼­ ½º·¹µå¸¦ »ç¿ëÇÏ´Â ¹æ¹ý ÀÔ´Ï´Ù. ¶È°°Àº ±â´ÉÀ» ¼öÇàÇÏ°Ô µË´Ï´Ù.

1. Runnable »ç¿ëÇϱâ

Runnable  °´Ã¼¿¡ ¸Þ½ÃÁö¸¦ Àü¼ÛÇÒ¼ö ÀÖ´Â ¹æ¹ýÀÌ Àִµ¥. À̶§ »ç¿ëÇÏ´Â °Ô Çڵ鷯 °´Ã¼ ÀÔ´Ï´Ù.

Handler ÀÇ post() ¸Þ¼­µå¸¦ ÀÌ¿ëÇؼ­ Runnable °´Ã¼¸¦ ½ÇÇà ½Ãų ¼ö ÀÖ½À´Ï´Ù.
 
	handler = new Handler();
	runnable1 = new PorgressRunnable();


	Thread thread1 = new Thread(new Runnable() {
		public void run() {
			//¿©±â¿¡ ÀÛ¾÷ÇÒ ³»¿ëÀ» ³Ö´Â´Ù.
			...
			handler.post(runnable1);	//runnable1 °´Ã¼(PorgressRunnable Ŭ·¡½º) ¿¡ °´Ã¼¸¦ Àü´ÞÇÑ´Ù.
			...
		}
	});
	
	thread1.start();


	public class ProgressRunnable implements Runnable {
		public void run() {
			//¿©±â¿¡ ÀÛ¾÷ÇÒ ³»¿ëÀ» ³Ö´Â´Ù.
		}
	}
	


ProgressRunnable Ŭ·¡½º¸¦ ½ÇÇàÇϱâ À§Çؼ­ handler.post(runnable1); ¸í·ÉÀ» ÀÌ¿ëÇØ È£ÃâÇÏ´Â ÇÔ¼ö ¿¹Á¦ ÀÔ´Ï´Ù.

 
¡Ø Ȥ½Ã µµ¿òÀÌ µÇ¼Ì´Ù¸é ´ñ±Û¿¡ ÇѸ¶µð ³²°ÜÁÖ¼¼¿ä!
ÀÛ¼ºÀÚ   ºñ¹Ð¹øÈ£
ÀÚµ¿±Û ¹æÁö     (ÀÚµ¿±Û ¹æÁö ±â´ÉÀÔ´Ï´Ù.)
³»¿ë   ´ñ±Û´Þ±â 
À̸ÞÀÏ ¹®ÀÇ : cak0280@nate.com  
Copyright 2000 By ENTERSOFT.KR All Rights Reserved.