学习《操作系统》的时候,经常讨论进程同步问题,目的就是在访问共享内存的时候不出错。
可是学习编程这么久了,我还不会定义一个能在两个进程之间共享的变量呢,真是郁闷!!!!所以学习操作系统这部分知识的时候,也是似懂非懂,无法亲自做实验。请高手叫我如何定义一个变量,可以在一个程序的n个副本(进程)之间共享。

解决方案 »

  1.   

    need static static String name="tomuno"
      

  2.   

    synchronized
     像Vector就可以
      

  3.   

    关于synchronized 
    这个关键字出现的目的是为了让几个线程能同步,举一个最简单的例子。一个电影院有20张票要卖,它有3个售票员。 
    写个程序来证实一下不用synchronized的结果好了,需要使用sleep()函数来制造出这种可能(线程的执行时机谁也不能预料)出现的情况: 
    public class Sell 

    public static void main(String [] args) 

    SellThread sell = new SellThread(); 
    Thread sell1 = new Thread(sell,"sellman1"); 
    Thread sell2 = new Thread(sell,"sellman2"); 
    Thread sell3 = new Thread(sell,"sellman3"); 
    sell1.start(); 
    sell2.start(); 
    sell3.start(); 

    } class SellThread implements Runnable 

    private int i = 20; 
    public void run() 

    while(true) 

    if( i > 0) 

    try 

    Thread.sleep(100); 
    } catch(Exception e) 

    } System.out.println(Thread.currentThread().getName() + " sell " + i--); 



    } 结果一共卖掉了22张票(估计电影院以为无缘无故多收了门票钱会很高兴,不过一会也许就要面对愤怒的顾客了....) 
    这个时候我们的synchronized应该发挥作用了^^修改程序如下: 
    public class Sell2 

    public static void main(String [] args) 

    SellThread sell = new SellThread(); 
    Thread sell1 = new Thread(sell,"sellman1"); 
    Thread sell2 = new Thread(sell,"sellman2"); 
    Thread sell3 = new Thread(sell,"sellman3"); 
    sell1.start(); 
    sell2.start(); 
    sell3.start(); 

    } class SellThread implements Runnable 

    private int i = 20; 
    String a = "now ok!"; 
    public void run() 

    while(true) 

    synchronized(a) 

    if( i > 0) 

    try 

    Thread.sleep(100); 
    } catch(Exception e) 

    } System.out.println(Thread.currentThread().getName() + " sell " + i--); 




    } 这样就好了只会卖20张票了