java基础之线程的同步(同步块和同步方法的使用)


//同步分为:同步块和同步方法。
//每个class都有一个锁或叫做监视器

// 1.同步块的实现:
class SellTickets implements Runnable{
 public int i = 50;
 public void run(){ 
  /*为了避免时间轮换导致的结果不可预料,就需要给方法加锁
  就可以避免出现class_5_54的数据超出范围现象*/
  
  synchronized (this) {  //此处称为 同步块
   while( i > 0){
    try {
     Thread.sleep(50);
    } catch (InterruptedException e) {
     e.printStackTrace();
    }  
    System.out.println("i : "+ i);
    i--;
   } 
  } 
 }
}

//  2.同步方法的实现:
class SellTickets2 implements Runnable{
 public int i = 50;
 public void run(){ 
  this.syn();
 }
 
 public synchronized void syn(){  //此处称为 同步方法
  while(i > 0){
   try {
   Thread.sleep(50);
  } catch (InterruptedException e) {
   e.printStackTrace();
  }  
  System.out.println("i : "+ i);
  i--;
  }
 }
}


public class Thread_Test {
 public static void main(String [] args){
  //用同步块来创建多线程
  SellTickets mt = new SellTickets(); 
  Thread t1 = new Thread(mt);
  Thread t2 = new Thread(mt);
  Thread t3 = new Thread(mt);
  Thread t4 = new Thread(mt);
  t1.start();
  t2.start();
  t3.start();
  t4.start();
  
  
  //用同步方法来创建多线程
  SellTickets2 st = new SellTickets2();
  Thread tt1 = new Thread(st);
  Thread tt2 = new Thread(st);
  Thread tt3 = new Thread(st);
  Thread tt4 = new Thread(st);
  tt1.start();
  tt2.start();
  tt3.start();
  tt4.start();
 }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值