public class SynchronizedTest { public static void main(String[] args) throws Exception { Stack s = new Stack();//实例化一个栈对象 s.print();//将栈中所有元素输出到控制台 Thread t1 = new PushThread(s);//利用多态实例化一个线程 Thread t2 = new PopThread(s); t1.start(); t2.start(); Thread.sleep(10000);//休眠10秒钟 s.print(); } } /*定义一个栈*/ class Stack { char[] data = { ‘A‘, ‘B‘, ‘C‘, ‘D‘ };//定义一个字符数组 int index = 2;//假设当前索引为2 /*利用synchronized实现加锁功能*/ public synchronized void push(char ch) { System.out.println(ch + " pushed!"); data[index] = ch; try { Thread.sleep(5000); } catch (InterruptedException e) { } index++; System.out.println("1:" + index); } /*利用synchronized实现加锁功能*/ public synchronized void pop() { System.out.println("2:" + index); index--; System.out.println("3:" + index); System.out.println(data[index] + " poped!"); data[index] = ‘ ‘; } /*输出字符数组元素到控制台*/ public void print() { for (int i = 0; i < data.length; i++) { System.out.print(data[i] + " "); } System.out.println(); } } /*定义一个入栈的线程*/ class PushThread extends Thread { Stack s; public PushThread(Stack s) { this.s = s; } public void run() { s.push(‘C‘); } } /*定义一个出栈的线程*/ class PopThread extends Thread { Stack s; public PopThread(Stack s) { this.s = s; } public void run() { s.pop(); } }
Java--Synchronized源代码测试,布布扣,bubuko.com
原文:http://blog.csdn.net/u011131296/article/details/21100055