day11综合练习

/*
1,4个窗口分别卖100张票
class Ticket extends Thread
{
 public void run()
 {
  for (int x = 1;x <= 100 ;x++ )
  {
   System.out.println(this.getName()+x);
  }
 }
}
class day11
{
 public static void main(String[] args)
 {
  new Thread(new Ticket()).start();
  new Thread(new Ticket()).start();
 }
}

2,4个窗口共卖100张票
注意安全问题,使用两种方式解决
class Ticket implements Runnable
{
 private int ticket = 100;
 public void run()
 {
  while (true)
  {
   synchronized (this)
   {
    if(ticket > 0)
    {
     System.out.println(Thread.currentThread().getName()+ (ticket--));
    }
   }
  }
 }
}
class day11
{
 public static void main(String[] args)
 {
  Ticket ticket = new Ticket();
  new Thread(ticket).start();
  new Thread(ticket).start();
  new Thread(ticket).start();
  new Thread(ticket).start();
 }
}

3,两个帐户向金库存钱,分别存入300,存3次
class Bank implements Runnable
{
 private int sum = 0;
 public void run()
 {
  for (int x = 0;x < 3;x++)
  {
   synchronized (this)
   {
    System.out.println(Thread.currentThread().getName()+(sum +=100));
   }
  }
 }
}
class day11
{
 public static void main(String[] args)
 {
  Bank bank = new Bank();
  new Thread(bank).start();
  new Thread(bank).start();
 }
}
4,单例设计模式,注意安全问题
//饿汉式
class Single
{
 private final Single single = new Single();
 public Single getInstance()
 {
  return single;;
 }
}
//懒汉式
class Single
{
 private Single single = null;
 public Single getInstance()
 {
  if (single == null)
  {
   synchronized (this)
   {
    if (single == null)
    {
     this.single = new Single;
     return single;
    }
   }
  }
  else
   return single;
 }
}
5,写一个死锁程序
*/
class DeadLock implements Runnable
{
 private boolean flag;
 DeadLock(boolean flag)
 {
  this.flag = flag;
 }
 public void run()
 {
  if (flag)
  {
   while (true)
   {
    synchronized (l.a)
    {
     System.out.println("if lock a");
     synchronized(l.b)
     {
      System.out.println("if lock b");
     }
    }
   }
  }
  else
  {
   while (true)
   {
    synchronized (l.b)
    {
     System.out.println("else lock b");
     synchronized (l.a)
     {
      System.out.println("else lock a");     
     }
    }
   }
  }
 }
}
class l
{
 static Object a = new Object();
 static Object b = new Object();
}
class day11
{
 public static void main(String[] args)
 {
  Object a = new Object();
  Object b = new Object();
  new Thread(new DeadLock(true)).start();
  new Thread(new DeadLock(false)).start();
 }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值