void join()
//작업이 모두 끝날 때 까지 기다린다.
void join(long millis)
//천분의 일초 동안 기다린다.
void join(long millis, int nanos)
//천분의 일초 + 나노초 동안 기다린다.
class ThreadTest{
static long startTime = 0;
public static void main(String args[])
{
ThreadTest1 th1 = new ThreadTest1();
ThreadTest2 th2 = new ThreadTest2();
th1.start();
th2.start();
startTime = System.currentTimeMillis();
//전역변수에 값 할당
try
{
th1.join();
//mian쓰레드가 th1의 작업이 끝날 때 까지 기다린다.
th2.join();
//main쓰레드가 th2의 작업이 끝날 때 까지 기다린다.
} catch(InterruptedException e) { }
System.out.println("소요시간:" +
(System.currentTimeMillis() - ThreadTest.startTime));
}//main
}
class TestThread1 extends Thread{
public void run()
{
for(int i=0; i<300; i++)
{
System.out.println("-");
}
}//run*(
}
class TestThread2 extends Thread{
public void run()
{
for(int i=0; i<300; i++)
{
System.out.println("\");
}
}//run*(
}
public void run()
{
while(true)
{
try
{
Thread.sleep(10* 1000); //10초를 기다린다.
}
catch (InterruptedException e)
{
System.out.println("Awaken by interrupt().");
}
gc();
// garbage collection을 수행한다.
// 사용하지 않느 객체 제거.
System.out.println("Garbage collected. Free Memory:"
+ freeMemory());
}
}
for(int i=0; i<20; i++)
{
reguiredMemory = (int)(Math.random()*10) * 20;
/*
필요한 메모리가 사용할 수 있는 양보다 적거나
전체 메모리의 60%이상 사용했을 경우 gc를 깨운다.
*/
if(gc.freeMemory() < requiredMemory \\
gc.freeMemory() < gc.totalMemory() * 0.4)
{
gc.interrupt(); //잠자고 있는 쓰레드 gc를 깨운다.
try
{
gc.join(100);
//join을 사용하여 gc가 지울 시간을 줘야함
}
catch(interruptedException e) { }
}
gc.usedMemory += requiredMemory;
System.out.println("useMemory:" + gc.usedMemory);
}
남은 시간을 다음 쓰레드에게 양보하고, 자신(현재 쓰레드)은 실행대기한다.
static 메서드이기에 자기 자신에게만 사용이 가능하다.
yiled()와 interrupt()를 적절히 사용하면, 응답성과 효율을 높일 수 있다.
class ThreadTest implements Runnable
{
boolean suspended = false;
boolean stopped = false;
Thread th;
ThreadTest(String name)
{
th = new Thread(this, name);
}
public void run()
{
while(!stopped)
{
if(!suspended)
{
/* 작업 수행 */
try
{
Thread.sleep(1000);
} catch (interruptedException e) {}
}
else
{
Thread.yield();
//일시정지 동안에 남은 시간을 다음 쓰레드에 양보
}//if
}//while
}//run
}//main
yield는 OS스케줄러가 관리하기 때문에 큰 효과가 없을 수도 있다.