ex)
package com.test.testapplication; public class TestApplication { public static void main(String [] args) { TestApplication test = new TestApplication(); test.doTest(); } private int count; StringBuffer sBuffer = new StringBuffer(); StringBuilder sBuilder = new StringBuilder(); private void doTest() { count=0; ThreadSample t1= new ThreadSample("t1"); ThreadSample t2= new ThreadSample("t2"); System.out.println("t1 : state :" + t1.getState()); t1.start(); System.out.println("t1 : state :" + t1.getState()); try { Thread.sleep(1000); } catch (InterruptedException e1) { e1.printStackTrace(); } System.out.println("t1 : state :" + t1.getState()); try { t1.join(); }catch(InterruptedException e ) { e.printStackTrace(); } t1.interrupt(); System.out.println("t1 : state :" + t1.getState()); } /*참조해야할 변수가 여러개일 경우 , 서로 다른 lock을 사용한다.*/ private Object builderLock = new Object(); class ThreadSample extends Thread{ public ThreadSample(String name) { super(name); } @Override public void run() { int loop = 0; while( loop < 10) { ++loop; synchronized(builderLock) { //System.out.println( this.getName() + " run!" + " count : "+(count++)); try { Thread.sleep(5000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } } }
출처 : 자바의 신
'java' 카테고리의 다른 글
FileWriter 및 BufferedWriter 텍스트기반 처리 (0) | 2019.09.22 |
---|---|
FileFilter , FileNameFilter interface (0) | 2019.09.21 |
synchronized 정리 (0) | 2019.09.21 |
Thread Priority 와 Daemon Thread (0) | 2019.09.17 |
Runnable interface와 Thread class (0) | 2019.09.17 |