黑马程序员_多线程

------- android培训java培训、期待与您交流! ----------


多线程:

实现多线程的方式有两种:
1,继承Thread类,重写run()方法,新建子类对象,调用start()方法开启线程,


class T extend Thread()
{
   public void run()
   {
       for(int i=0;i++;i<100)
       {
          system.out.println(this.getName()+"   "+i);
       }
   }
}


class test
{
 public static void main(String[] args)
{
   T t1 = new ();
   t2 = new();
   t1.start();
   t2.start();
}


}






2.实现Runable接口,重写run()方法,新建子类对象,new Thread 类 将子类对象作为参数传进去


class T implements Thread()
{
   public void run()
   {
       for(int i=0;i++;i<100)
       {
          system.out.println(this.getName()+"   "+i);
       }
   }
}


class test
{
 public static void main(String[] args)
{
   Thread t1 = new Thread(new T() );
   Thread t2 = new Thread(new T() );
   t1.start();
   t2.start();
}
}




线程同步的方法有:


将要共同执行的语句放进
sysnchroinzed(任意对象)
{
}
语句块中,或者在方法上加上synchronized修饰符


创建lock对象,使用lock.lock()方法进行加锁,我们要在创建一个Condition 对象作为这个锁的监听器


比如:
class BoundedBuffer {
   Lock lock = new ReentrantLock();
   Condition condition = lock.newCondition(); 
   
   public void put(Object x) throws InterruptedException {
     lock.lock();  //上锁
     try {
      condition.await(); //使线程处于等待状态


    方法体;  


      condition.signal();  //  唤醒线程
     } finally {
       lock.unlock(); //释放锁
     }
   }





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值