Java线程同步示例

文章用实例代码展示了Java中多线程访问共享资源线程同步 的重要性。

分别通过在两个线程中同时访问(调用get_id*方法)经过同步处理(lock及Synchronized)的共享资源(tmp)及未经过同步处理的共享资源(tmp)来说明同步处理的的作用。

 

main中分两部分:
1)前半部分,non-synchronization部分用来测试没有做同步处理的代码段,运行结果应该是
After thread #1 call get_id(), id=1 After thread #2 call get_id(), id=1
2)后半部分,synchronization部分用来测试做过同步处理的代码段,运行结果应该是
After thread #1 call get_id(), id=1 After thread #2 call get_id(), id=2
参考资料:
-1-关于sleep和wait区别看一下这个: http://wurd.javaeye.com/blog/174563。
-2-关于synchronized可以看一下这篇:http://www.wangchao.net.cn/bbsdetail_148670.html,比较明了。
-3-关于Java线程同步可以看一下这个:http://lavasoft.blog.51cto.com/62575/27069,很详细。

/******************************************************************************** *FileName: Thread_sync.java *Date: 2010/01/12 *Intention: Test thread synchronization tools in java. *Input: *Output: * in non-synchronization version * After thread #1 call get_id(), id=1 * After thread #2 call get_id(), id=1 * in synchronization version * After thread #1 call get_id(), id=1 * After thread #2 call get_id(), id=2 * *DevelopmentEnv: Netbeans 6.8, Jdk 1.6. ********************************************************************************/ class Counter { private final static Object lock = new Object(); private static int count = 0; public int get_id() { int tmp = count; ++tmp; try { Thread.sleep(1000); } catch(Exception e) { } count = tmp; return count; } public int get_id_sync() { synchronized(lock) { int tmp = count; ++tmp; try { Thread.sleep(1000); } catch(Exception e) { } count = tmp; } return count; } } public class Thread_sync { private static int cnt = 0; static class Rab implements Runnable { public void run() { Counter c = new Counter(); System.out.println("After thread #" + (++cnt) + " call get_id(), id=" + c.get_id()); } } static class RabSync implements Runnable { public void run() { Counter c = new Counter(); System.out.println("After thread #" + (++cnt) + " call get_id_sync(), id=" + c.get_id_sync()); } } public static void main(String arg[]) { //non-synchronization version //Run result: // After thread #1 call get_id(), id=1 // After thread #2 call get_id(), id=1 Thread_sync.Rab rab = new Thread_sync.Rab(); Thread t1 = new Thread(rab); Thread t2 = new Thread(rab); t1.start(); t2.start(); //synchronization version //Run result: // After thread #1 call get_id(), id=1 // After thread #2 call get_id(), id=2 // Thread_sync.RabSync rabsync = new Thread_sync.RabSync(); // Thread t1 = new Thread(rabsync); // Thread t2 = new Thread(rabsync); // t1.start(); // t2.start(); } }

你可能感兴趣的:(Java,java,thread,exception,netbeans,class,object)