A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© myself123 中级黑马   /  2015-8-25 10:30  /  427 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

1、同步代码块
格式:synchronized(对象)
                {
                        需同步的代码;
                }
锁可以是任意对象。
2、同步方法
格式:修饰词 synchronized 返回值类型 函数名(参数列表)
                {
                        需同步的代码;
                }
锁为this,即本类对象。
另外,静态同步方法的锁为类名.class。
3、代码:
  1. class Ticket implements Runnable {

  2.         private int num = 100;
  3.         boolean flag = true;

  4.         //覆盖run方法,创建任务
  5.         @Override
  6.         public void run() {

  7.                 if (flag) {
  8.                         while (true) {
  9.                                 //同步代码块
  10.                                 synchronized (this) {
  11.                                         if (num > 0) {
  12.                                                 try {
  13.                                                         Thread.sleep(10);
  14.                                                 } catch (InterruptedException e) {
  15.                                                 }
  16.                                                 System.out.println(Thread.currentThread().getName()
  17.                                                                 + "同步代码块" + num--);
  18.                                         }
  19.                                 }
  20.                         }
  21.                 } else {
  22.                         while (true) {
  23.                                 this.show();
  24.                         }
  25.                 }
  26.         }
  27.        
  28. //同步函数
  29.         public synchronized void show() {

  30.                 if (num > 0) {
  31.                         try {
  32.                                 Thread.sleep(10);
  33.                         } catch (InterruptedException e) {
  34.                         }
  35.                         System.out.println(Thread.currentThread().getName() + "同步函数"
  36.                                         + num--);
  37.                 }
  38.         }

  39. }

  40. public class TicketDemo {

  41.         public static void main(String[] args) {

  42.                 Ticket t = new Ticket();

  43.                 Thread t1 = new Thread(t);
  44.                 Thread t2 = new Thread(t);

  45.                 t1.start();
  46.                 try {
  47.                         Thread.sleep(10);
  48.                 } catch (InterruptedException e) {
  49.                 }
  50.                 t.flag = false;
  51.                 t2.start();
  52.         }

  53. }
复制代码



2 个回复

倒序浏览
写的不错,赞一个
回复 使用道具 举报

感谢感谢
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马