生病的吉娃娃

欢迎使用WSBLog,有什么问题或意见请给我反馈,谢谢。

导航菜单

« [转贴]张宁宁和森理世,差距在哪里? 龙的传人 »

Java的线路同步示例(synchronized、wait和notify)

从网上找到的代码(随便改的)。比较清晰地展示了wait和notify的运行机制。

package com.wubuku.mytest;

public class ThreadingExample {

    public static void main(String args[]) {
        Thread[] threads = new Thread[2];
        for (int count = 0; count < threads.length; count++) {
            threads[count] = new ThreadCounter(count);
            threads[count].start();
        }
    }

    private static class ThreadCounter extends Thread {
        /**
         * 在没有同步的情况下,这个方法会打印出不定顺序的数字
         */
        public static void count() {
            for (int count = 1; count <= 5; count++)
                System.out.print(count + " ");
        }

        public static Object synchronizeVariable = "locking variable";

        private int threadNo;

        public ThreadCounter(int threadNo) {
            this.threadNo = threadNo;
        }

        public void run() {
            countWithSync();
        }

        /**
         * 在有同步的情况下,能打印出这样顺序的数字: 1 1 2 2 3 3 4 4 5 5
         */
        private void countWithSync() {
            synchronized (synchronizeVariable) {
                for (int count = 1; count <= 5; count++) {
                    System.out.println("[thread_" + threadNo + " print:]"
                            + count + " ");
                    synchronizeVariable.notifyAll();

                    if (count < 5) {
                        System.out.println("[thread_" + threadNo
                                + " sleep zzz...] ");

                        try {
                            synchronizeVariable.wait();
                        } catch (InterruptedException error) {
                        }

                        System.out.println("[thread_" + threadNo + " wakup!] ");
                    }
                }
            }

        }
    }
}

  • quote 6.aaaa
  • 改了优先级会怎样?
  • 2008-6-16 15:30:00
  • quote 4.sdf
  • 你好,这是我的到访留言,
    欢迎回访:)再走走,看看我的。。
    听景777-属于个人的Blog
    地址1 http://shunhill.cn/
    地址2 www2.wp-zz.cn
  • 2007-8-4 16:35:00

发表评论:

Verificaton_Code

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点.

网站目录

Google

日历

最新评论

最近发表

Powered By WSBLog 1.6 Beta Build 60420

Copyright 2004-2006 wubuku.com. Some Rights Reserved.