1 import java.util.concurrent.locks.Lock; 2 import java.util.concurrent.locks.ReentrantLock; 3 4 public class RunnableTest2 { 5 // private StringBuilder sb = new StringBuilder(); 6 private StringBuffer sb = new StringBuffer(); 7 inc i1 = new inc(); 8 dec d1 = new dec(); 9 private Lock lock = new ReentrantLock(); 10 private boolean ok = false; 11 public static void main(String[] args) throws InterruptedException { 12 RunnableTest2 tr = new RunnableTest2(); 13 double time = System.currentTimeMillis(); 14 for(int i=0;i<1;i++) { 15 new Thread(tr.i1).start(); 16 new Thread(tr.d1).start(); 17 18 } 19 // System.out.println(System.currentTimeMillis()-time); 20 } 21 22 private void incc() { 23 // synchronized(sb) { 24 lock.lock(); 25 for(int i=0;i<7;i++) { 26 char at = "freedom".charAt(i); 27 sb.append(at+""); 28 29 } 30 31 System.out.println(Thread.currentThread().getName()+sb.toString()); 32 sb.delete(0, 7); 33 // } 34 lock.unlock(); 35 } 36 37 private void decc() { 38 // synchronized(sb) { 39 lock.lock(); 40 41 for(int i=0;i<7;i++) { 42 char at = "freedom".charAt(i); 43 sb.append(at+""); 44 45 } 46 47 System.out.println(Thread.currentThread().getName()+sb.toString()); 48 sb.delete(0, 7); 49 // } 50 lock.unlock(); 51 52 } 53 54 class inc implements Runnable { 55 public void run() { 56 // TODO Auto-generated method stub 57 for(int i=0; i<100000; i++) 58 incc(); 59 } 60 } 61 62 class dec implements Runnable { 63 public void run() { 64 // TODO Auto-generated method stub 65 for(int i=0; i<100000; i++) 66 decc(); 67 } 68 } 69 }
打印结果各有不同
两个线程与stringbuffer和stringbuiler以及lock synchronized线程测试
原文:http://www.cnblogs.com/freed0m/p/4986553.html