Javaの同期コードブロックと同期方法

2399 ワード

1 じっと見つめる
原子性とは,1セグメントのコードが実行されるか,実行されないか,実行の一部が中断されることはない.このコードは原子のように分割できないという意味だ.
同期の意味:マルチスレッドはコード実行のキーの上で、互いにメッセージを通じて、互いに協力して、共に任務を正しく完成します.
同期コードブロック構文:
synchronized(  )
{
            ;
}

同期メソッド構文:
      synchronized          (  )
{
           ;
}

二 コードブロックを同期してチケット販売機能を完了する
1 コード#コード#
public class threadSynchronization
{
    public static void main( String[] args )
    {
        TestThread t = new TestThread();
        //        ,      
        new Thread( t ).start();
        new Thread( t ).start();
        new Thread( t ).start();
        new Thread( t ).start();
    }
}
class TestThread implements Runnable
{
    private int tickets = 5;
    @Override
    public void run()
    {
        while( true )
        {
            synchronized( this )
            {
                if( tickets <= 0 )
                    break;

                try
                {
                    Thread.sleep( 100 );
                }
                catch( Exception e )
                {
                    e.printStackTrace();
                }
                System.out.println( Thread.currentThread().getName() + "   " + tickets );
                tickets -= 1;

            }
        }
    }
}

2 うんてん
Thread-0   5
Thread-3   4
Thread-3   3
Thread-2   2
Thread-2   1

三 同期方法チケット購入機能完了
1 コード#コード#
public class threadSynchronization
{
   public static void main( String[] args )
   {
      TestThread t = new TestThread();
      //        ,         
      new Thread( t ).start();
      new Thread( t ).start();
      new Thread( t ).start();
      new Thread( t ).start();
   }
}
class TestThread implements Runnable
{
   private int tickets = 5;

   public void run()
   {
      while( tickets > 0 )
      {
         sale();
      }
   }
   public synchronized void sale()
   {
      if( tickets > 0 )
      {
         try
         {
            Thread.sleep( 100 );
         }
         catch( Exception e )
         {
            e.printStackTrace();
         }
         System.out.println( Thread.currentThread().getName() + "   "
               + tickets );
         tickets -= 1;
      }
   }
}

2 うんてん
Thread-0   5
Thread-0   4
Thread-3   3
Thread-2   2
Thread-1   1