首页 > 编程 > Java > 正文

Java同步代码块和同步方法原理与应用案例详解

2019-11-26 08:27:09
字体:
来源:转载
供稿:网友

本文实例讲述了Java同步代码块和同步方法。分享给大家供大家参考,具体如下:

一 点睛

所谓原子性:一段代码要么执行,要么不执行,不存在执行一部分被中断的情况。言外之意是这段代码就像原子一样,不可拆分。

同步的含义:多线程在代码执行的关键点上,互通消息,相互协作,共同把任务正确的完成。

同步代码块语法:

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

更多java相关内容感兴趣的读者可查看本站专题:《Java进程与线程操作技巧总结》、《Java数据结构与算法教程》、《Java操作DOM节点技巧总结》、《Java文件与目录操作技巧汇总》和《Java缓存操作技巧汇总

希望本文所述对大家java程序设计有所帮助。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表