大侠给个能运行的例子我学学!!
  先谢谢了!!!!!!!!

解决方案 »

  1.   

    package chapter07;
    public class OnlyOneInMethod extends Object {
    private String objID; public OnlyOneInMethod(String objID) {
    this.objID = objID;
    } public synchronized void doStuff(int val) {
    print("entering doStuff()");
    int num = val * 2 + objID.length();
    print("in doStuff() - local variable num=" + num); // slow things down to make observations
    try { Thread.sleep(2000); } catch ( InterruptedException x ) { } print("leaving doStuff()");
    } public void print(String msg) {
    threadPrint("objID=" + objID + " - " + msg);
    } public static void threadPrint(String msg) {
    String threadName = Thread.currentThread().getName();
    System.out.println(threadName + ": " + msg);
    } public static void main(String[] args) {
    final OnlyOneInMethod ooim = new OnlyOneInMethod("obj1"); Runnable runA = new Runnable() {
    public void run() {
    ooim.doStuff(3);
    }
    }; Thread threadA = new Thread(runA, "threadA");
    threadA.start(); try { Thread.sleep(200); } catch ( InterruptedException x ) { } Runnable runB = new Runnable() {
    public void run() {
    ooim.doStuff(7);
    }
    }; Thread threadB = new Thread(runB, "threadB");
    threadB.start();
    }
    }
      

  2.   

    刚巧以前答过这个问题,有源码。
    package ProducerConsumer;
    import java.io.*;
    class CircularBuffer
    {
    int bufsize;
    int[] store;
    int numOfEntries=0;
    int front=0;
    int back=0;

    CircularBuffer(int n)
    {
    bufsize=n;
    store=new int[bufsize];

    }
    synchronized void put(int obj)throws Exception{
    if(numOfEntries==bufsize)
    {
    System.out.println("Producer waiting");

    wait();

    }
    store[back]=obj;
    back++;
    if(back==bufsize)  back=0;
    else {numOfEntries++;
    System.out.println("putting   "+   obj);

    notify();
    }

    }

    synchronized int get() throws Exception{
    int result=0;
    if(numOfEntries==0)
    {
    System.out.println("Consumer waiting");
    wait();
    }

    else{
    result=store[front];
    front++;
    if(front==bufsize) front=0;



    numOfEntries--;
    System.out.println("getting   "+result);//;
    notify();
    }
    return result;



    }
    }
      

  3.   

    package ProducerConsumer;
    class Consumer extends Thread
    {
    CircularBuffer cbc=null;


     Consumer(CircularBuffer cb)
    {cbc=cb;}
    public void run(){
    for(int i=0;i<=50000;i++)
    try{
    cbc.get();
    }
    catch (Exception err){

    }

    }

    }
      

  4.   

    package ProducerConsumer;
    import java.io.*;
    class ProCum{
    public static void main(String[] args){

    CircularBuffer cb=new CircularBuffer(20);

    //因为要调用的两个方法put和get是排斥,所以调用时由同一个对象调用,所以
    ?/都是cb,注意注意!!!!!!

    Producer pro=new Producer(cb);
    Consumer con=new Consumer(cb);
    //
    Thread a=null;
    Thread b=null;

    a=new Thread(pro);

    b=new Thread(con);
    b.start();
    a.start();

    }
    }
      

  5.   

    class One 
    {       
      synchronized void display(int num)  
      //可以将synchronized去掉以观察效果
      { 
           System.out.print(""+num);
           try 
           {
              Thread.sleep(1000); 
           }   
           catch(InterruptedException e)  
           {
               System.out.println("中断");
           }
           System.out.println(" 完成");
     }
    }class Two implements Runnable 
    {
      int number; 
      One one;
      Thread t;
      public Two(One one_num, int n)   
      {
          one=one_num; 
          number=n;
          t=new Thread(this);
          t.start();
       }
       public void run() 
       {
            one.display(number);
       }
    }public class exec 
    {
       public static void main(String args[]) 
       {
           One one=new One();
           int digit=10;
           Two s1=new Two(one,digit++);
           Two s2=new Two(one,digit++);
           Two s3=new Two(one,digit++);
           try
           {
              s1.t.join();
              s2.t.join();
              s3.t.join(); 
           }
           catch(InterruptedException e)
           {
              System.out.println("中断");
           }
        }
    }
      

  6.   

    不好意思,上次贴漏了producer的代码,下面补回:
    package ProducerConsumer;
    class Producer extends Thread
    {
    CircularBuffer cbp=null;


     Producer(CircularBuffer cb){cbp=cb;}
    public void run(){
    for(int i=0;i<=50000;i++)
    try{
    cbp.put(i);
    }
    catch (Exception err){
    //System.

    }

    }
    // public static void main(String[] args) {}
    }
      

  7.   

    package net.hygx;
    class Producer implements Runnable
    {
    Q q;
    public Producer(Q q)
    {
    this.q=q;
    }
    public void run()
    {
    int i=0;
    while(true)
    {
    /*这个是用synchronized(q)代码块使多线程同步。
    synchronized(q)
    {
    if(q.bFull)
    try{q.wait();}catch(Exception e){}
    if(i == 0)
    {
    q.name="zhangsan";
    try{Thread.sleep(1);}catch(Exception e){}
    q.sex="male";
    }
    else
    {
    q.name="lisi";
    q.sex="female";
    }
    q.bFull = true;
    q.notify();
    }
    */
    if(i == 0)
    q.put("zhangsan","male");
    else
    q.put("lisi","female"); i = (i+1)%2;
     
    }
    }
    }class Consumer implements Runnable
    {
    Q q;
    public Consumer(Q q)
    {
    this.q=q;
    }
    public void run()
    {
    while(true)
    {
    /*
                  synchronized()代码块方法实现多线程同步。
    synchronized(q)
    {
    if(!q.bFull)
                    try{q.wait();}catch(Exception e){}
    System.out.print(q.name);
    System.out.println(":"+q.sex);
    q.bFull = false;
    q.notify();
    }*/
    q.get(); }
    }
    }class  Q
    {
    private String name="unknown";
    private String sex="unknown";
    private boolean bFull = false;
         /*下面是用synchronized方法实现多线程同步。          */
    public synchronized void put(String name,String sex)
    {
    if(bFull)
    try{wait();}catch(Exception e){}
    this.name = name;
    try{Thread.sleep(1);}catch(Exception e){}
    this.sex = sex;
    bFull = true;
    notify();
    }
    public synchronized void get()
    {
    if(!bFull)
    try{wait();}catch(Exception e){}
    System.out.print(name);
    System.out.println(":"+sex);
    bFull = false;
    notify();
    }
    }class ThreadCommunation
    {
    public static void main(String [] args)
    {
    /*Q q=new Q();
    new Thread(new Producer(q)).start();
    new Thread(new Consumer(q)).start();
    */
    ThreadTest tt = new ThreadTest();
    new Thread(tt).start();
    for(int i = 0;i<100;i++)
    {
    if(i == 50)
    tt.stopMe();
    System.out.println("main()is running!");
    }
    }
    }class ThreadTest implements Runnable
    {
    private boolean bStop = false;
    public void stopMe()
    {
    bStop = true;
    } public void run()
    {
    while(!bStop)
    {
    System.out.println(Thread.currentThread().getName()+"is running!");
    }
    }
    }
    注意:

    Thread t;
    synchronized(o)线程t得到对象o,的lock旗标,那么上例中,
    o.wait();t 被放置在对象o,的等待线程池中,自动释放o的锁旗标。o.notify();当另外的线程执行对象o的notify方法后,t可能会从o的等待池中释放并移动到等待对象o的锁旗标的线程中,当t得到锁旗标时,就会执行下去。……
      

  8.   

    synchronized的用法 
     synchronized 关键字,它包括两种用法:synchronized 方法和 synchronized 块。
    1. synchronized 方法:通过在方法声明中加入 synchronized关键字来声明 synchronized 方法。如:
    public synchronized void accessVal(int newVal);
    synchronized 方法控制对类成员变量的访问:每个类实例对应一把锁,每个 synchronized 方法都必须获得调用该方法的类实例的锁方能执行,否则所属线程阻塞,方法一旦执行,就独占该锁,直到从该方法返回时才将锁释放,此后被阻塞的线程方能获得该锁,重新进入可执行状态。这种机制确保了同一时刻对于每一个类实例,其所有声明为 synchronized 的成员函数中至多只有一个处于可执行状态(因为至多只有一个能够获得该类实例对应的锁),从而有效避免了类成员变量的访问冲突(只要所有可能访问类成员变量的方法均被声明为 synchronized)。
    在 Java 中,不光是类实例,每一个类也对应一把锁,这样我们也可将类的静态成员函数声明为 synchronized ,以控制其对类的静态成员变量的访问。
    synchronized 方法的缺陷:若将一个大的方法声明为synchronized 将会大大影响效率,典型地,若将线程类的方法 run() 声明为 synchronized ,由于在线程的整个生命期内它一直在运行,因此将导致它对本类任何 synchronized 方法的调用都永远不会成功。当然我们可以通过将访问类成员变量的代码放到专门的方法中,将其声明为 synchronized ,并在主方法中调用来解决这一问题,但是 Java 为我们提供了更好的解决办法,那就是 synchronized 块。
    2. synchronized 块:通过 synchronized关键字来声明synchronized 块。语法如下: 
    synchronized(syncObject) 
    synchronized 块是这样一个代码块,其中的代码必须获得对象 syncObject (如前所述,可以是类实例或类)的锁方能执行,具体机制同前所述。由于可以针对任意代码块,且可任意指定上锁的对象,故灵活性较高。 notify()及notifyAll()是Object的方法,与Object的wait()方法配合使用,而且这三个方法必须在同步块中调用.如下:
    在线程1中执行如下代码
    ...
    synchronized(obj1)      //1.进入同步块
    {
        try {
        ...
        obj1.wait();        //2.进入暂停状态
        }catch (InterruptedException exp) {}
    }
     
      

  9.   

    Java线程及同步(synchronized)样例代码
    import java.io.*;
    import java.util.*;
    import java.text.SimpleDateFormat;
    public class TestThread extends Thread
    {
        private static Integer threadCounterLock; //用于同步,防止数据被写乱
        private static int threadCount; //本类的线程计数器
        static
        {
            threadCount = 0;
            threadCounterLock = new Integer(0);
        }
        public TestThread()
        {
            super();
        }
        public synchronized static void incThreadCount()
        {
            threadCount++;
            System.out.println("thread count after enter: " + threadCount);
        }
        public synchronized static void decThreadCount()
        {
            threadCount--;
            System.out.println("thread count after leave: " + threadCount);
        }
        public void run()
        {
            synchronized(threadCounterLock) //同步
            {
                threadCount++;
                System.out.println("thread count after enter: " + threadCount);
            }
            //incThreadCount(); //和上面的语句块是等价的
            final long nSleepMilliSecs = 1000;  //循环中的休眠时间
            long nCurrentTime = System.currentTimeMillis();
            long nEndTime = nCurrentTime + 30000;  //运行截止时间
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try
            {
                while (nCurrentTime < nEndTime)
                {
                    nCurrentTime = System.currentTimeMillis();
                    System.out.println("Thread " + this.hashCode() + ", current time: " + simpleDateFormat.format(new Date(nCurrentTime)));
                    try
                    {
                        sleep(nSleepMilliSecs);
                    }
                    catch(InterruptedException ex)
                    {
                        ex.printStackTrace();
                    }
                }
            }
            finally
            {
                synchronized(threadCounterLock) //同步
                {
                    threadCount--;
                    System.out.println("thread count after leave: " + threadCount);
                }
                //decThreadCount();   //和上面的语句块是等价的
            }
        }
        public static void main(String[] args)
        {
            TestThread[] testThread = new TestThread[2];
            for (int i=0; i<testThread.length; i++)
            {
                testThread[i] = new TestThread();
                testThread[i].start();
            }
        }
    }