| Refresh | Home EGTry.com

lock on static class method


StaticThread.java

package egtry.thread;

import java.util.concurrent.atomic.AtomicLong;

public class StaticThread extends Thread {

	private static AtomicLong counter=new AtomicLong(10);

	public static void main(String[] args) throws Exception {
		StaticThread thread1=new StaticThread();
		thread1.start();
		StaticThread thread2=new StaticThread();
		thread2.start();
		StaticThread thread3=new StaticThread();
		thread3.start();
	
	}

	@Override
	public void run() {
		
		Thread t=Thread.currentThread();
		long id=t.getId();
		for(int i=0; i<5; i++) {
			Logger.append("thread "+id+",  message "+i);
			Sleep(10);
		}
		Logger.flush();
			
	}
	
	public static void Sleep(int ms) {
		try {
			Thread.sleep(ms);
			} catch (Exception e) {
				System.out.println(e.getMessage());
		}
	}
}

class LoggerRegular {
	private static StringBuffer buff=new StringBuffer();

	public static void flush() {
		
		System.out.println("Output Unit:\n"+ buff.toString());
		buff.setLength(0);
	}
	
	public static void append(String line) {
		buff.append(line+"\n");
	}
}

class Logger {
	private static ThreadLocal<StringBuffer> locals=new ThreadLocal<StringBuffer>();
	
	public static void flush() {
		StringBuffer buff=locals.get();
		System.out.println("Output Unit:\n"+ buff.toString());
		buff.setLength(0);
	}
	
	public static void append(String line) {
		StringBuffer buff=locals.get();
		if (buff==null) {
			buff=new StringBuffer();
			locals.set(buff);
		}
		buff.append(line+"\n");
	}
}


Output

Output Unit:
thread 10,  message 0
thread 10,  message 1
thread 10,  message 2
thread 10,  message 3
thread 10,  message 4

Output Unit:
thread 9,  message 0
thread 9,  message 1
thread 9,  message 2
thread 9,  message 3
thread 9,  message 4

Output Unit:
thread 8,  message 0
thread 8,  message 1
thread 8,  message 2
thread 8,  message 3
thread 8,  message 4