Chinaunix首页 | 论坛 | 博客
  • 博客访问: 522403
  • 博文数量: 151
  • 博客积分: 7010
  • 博客等级: 少将
  • 技术积分: 1405
  • 用 户 组: 普通用户
  • 注册时间: 2008-04-22 14:32
文章分类

全部博文(151)

文章存档

2011年(1)

2010年(23)

2009年(1)

2008年(126)

我的朋友

分类: Java

2008-05-10 09:13:33

线程同步可以有两种方式
一、采用同步代码块:就是用synchronized申明一个互斥变量
   class aa
   {
    public static void main(String[] args)
    {
     TestThread tt = new TestThread();
     new Thread(tt).start();
     new Thread(tt).start();
     new Thread(tt).start();
     new Thread(tt).start();
    }
   }
  
   class TestThread implements Runnable
   {
    int tickets = 10;
    String str = new String("");
  
    public void run()
    {
     synchronized (str)
     {
      while (tickets > 0)
      {
       System.out.println("TestThread: "
         + Thread.currentThread().getName() + "the tickets = "
         + tickets--);
      }
     }
    }
  
 
二、采用同步函数:用在方法前加上synchronized。同步函数其实是把this作为互斥变量
   class aa
   {
    public static void main(String[] args)
    {
     TestThread tt = new TestThread();
     new Thread(tt).start();
     new Thread(tt).start();
     new Thread(tt).start();
     new Thread(tt).start();
    }
   }
  
   class TestThread implements Runnable
   {
    int tickets = 10;
    String str = new String("");
  
    public void run()
    {
     while (true)
     {
      sale();
     }
    }
  
    synchronized public void sale()
    {
     while (tickets > 0)
     {
      System.out.println("TestThread: "
        + Thread.currentThread().getName() + "the tickets = "
        + tickets--);
     }
    }
  
阅读(635) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~