我只知道它有synchronized 方法和 synchronized 块
但不知道他们到底怎么用,他们的操作对象是什么?

解决方案 »

  1.   

    1.synchronized方法
    class Demo implements Runnable
    {
    private int ticket = 10 ;
    // 加入一个同步方法
    public synchronized void fun() 
    {
    // 把需要同步的地方放在同步方法之中
    if(this.ticket>0)
    {
    try
    {
    Thread.sleep(100) ;
    }
    catch (Exception e)
    {
    }
    System.out.println(Thread.currentThread().getName()+" --> 卖票:"+this.ticket--) ;
    }
    }
    public void run()
    {
    while(ticket>0)
    {
    this.fun() ;
    }
    }
    };
    public class ThreadDemo14
    {
    public static void main(String args[])
    {
    Demo d = new Demo() ;
    Thread t1 = new Thread(d,"售票点 A") ;
    Thread t2 = new Thread(d,"售票点 B") ;
    Thread t3 = new Thread(d,"售票点 C") ; t1.start() ;
    t2.start() ;
    t3.start() ;
    }
    };2.synchronized同步块
    class Demo implements Runnable
    {
    private int ticket = 10 ;
    public void run()
    {
    while(ticket>0)
    {
    // 加入同步块
    synchronized(this)
    {
    if(this.ticket>0)
    {
    try
    {
    Thread.sleep(100) ;
    }
    catch (Exception e)
    {
    }
    System.out.println(Thread.currentThread().getName()+" --> 卖票:"+this.ticket--) ;
    }
    }
    }
    }
    };
    public class ThreadDemo15
    {
    public static void main(String args[])
    {
    Demo d = new Demo() ;
    Thread t1 = new Thread(d,"售票点 A") ;
    Thread t2 = new Thread(d,"售票点 B") ;
    Thread t3 = new Thread(d,"售票点 C") ; t1.start() ;
    t2.start() ;
    t3.start() ;
    }
    };
      

  2.   

    楼主怎么没有结过贴! synchronized 修饰的部分 简单理解就是独自占有! 它用完了,别人才能用! 这个很好用的,随便找个代码给你吧!马士兵教程中有一个public class TestSycronized implements Runnable{

    int b = 100;public synchronized void m1() throws Exception{

    b =1000;

    Thread.sleep(5000);

    System.out.println("b ="+b);


    } public void m2(){
    System.out.println(b);

    }
    public synchronized  void run(){

    try{

    m1();
    }catch (Exception e){

    e.printStackTrace();

    }


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

    TestSycronized ts= new TestSycronized();

    Thread t =new Thread(ts) ;

    t.start();
    Thread.sleep(1000);

    ts.m2();
    }

    }