线程是一个程序内部的顺序控制流。
当一个线程锁定了一个方法的时候,其他线程可以通过其他方法修改值,所以,一定要保证所有有关这个变量的方法都要加锁。
同步实例:
<span style="font-family:Microsoft YaHei;"><span style="font-size:12px;">package thread; public class TT implements Runnable{ int b = 100 ; @Override public void run() { m1() ; } //只会锁定m1方法内的内容,不会锁定b public synchronized void m1() { b = 1000 ; try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("b = " + b); } public void m2() { System.out.println(b); } public static void main(String[] args) { TT t = new TT() ; Thread thread = new Thread(t) ; thread.start() ; try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } t.m2(); } } </span></span>
生产者与消费者实例:
<span style="font-family:Microsoft YaHei;">package thread; public class ProducerConsumer { public static void main(String[] args) { SyncStack ss = new SyncStack() ; Producer p = new Producer(ss) ; Consumer c = new Consumer(ss) ; new Thread(p).start(); new Thread(c).start(); } } class WoTou { int id ; WoTou(int id) { this.id = id ; } public String toString() { return "id = " + this.id ; } } class SyncStack { int index = 0 ; WoTou[] arrWt = new WoTou[6] ; public synchronized void push(WoTou wt) { while(index == arrWt.length) { try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } this.notify(); arrWt[index] = wt ; index ++ ; } public synchronized WoTou pop() { while(index == 0) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } this.notify(); index -- ; return arrWt[index] ; } } class Producer implements Runnable { SyncStack s = null ; public Producer(SyncStack s) { this.s = s ; } @Override public void run() { for(int i=0; i<20; i++) { WoTou wt = new WoTou(i) ; System.out.println("push : " + wt); s.push(wt); } } } class Consumer implements Runnable { SyncStack s = null ; public Consumer(SyncStack s) { this.s = s ; } @Override public void run() { for(int i=0; i<20; i++) { WoTou wt = s.pop() ; System.out.println("pop : " + wt); } } }</span>
原文地址:http://blog.csdn.net/benjamin_whx/article/details/44942293