java之多线程

1 线程的两种实现方式

   A 继承thread类

   B 实现runnable接口

2 同步

   synchronized(对象) {    }

  非静态的锁对象:方法中都能共享一个对象this

  静态的锁对象:所有对象都能共享一个对象,类.class

3 实例

  A:死锁

         public class DeadLock extends Thread {
         private boolean flag;
         public DeadLock(boolean flag){
              this.flag = flag;
         }
         public void run() {
              if(this.flag){
               synchronized (MyLock.objA) {
                System.out.println("objA");
                synchronized (MyLock.objB) {
                 System.out.println("objB");
            }
       }
  }
              else{
           synchronized (MyLock.objB) {
            System.out.println("objB");
            synchronized (MyLock.objA) {
             System.out.println("objA");
            }
           }
      }
     }
    }

B.  静态锁对象

public class Tickets implements Runnable {
 private static int tickets = 50;
 public void run() {

  while(true){
   for (int i = 0; i <= 50; i++) {
    if(i % 2 == 0){
     synchronized(Tickets.class){
      if(tickets > 0){ 
       try {
        Thread.sleep(100);
       } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
       }
       System.out.println(Thread.currentThread().getName()+ ":售出了第" + tickets-- + "张火车票!");
      }  
     }
    }
    else{
     method2();
    }
   }
  }
 }
 public synchronized void method(){
   if(tickets > 0){
    try {
     Thread.sleep(100);
    } catch (InterruptedException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
    System.out.println(Thread.currentThread().getName()+ ":售出了第" + tickets-- + "张火车票!");
   } 
 }
 public static synchronized void method2(){
  if(tickets > 0){
    
   try {
    Thread.sleep(100);
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   System.out.println(Thread.currentThread().getName()+ ":售出了第" + tickets-- + "张火车票!");
  }
}

}


你可能感兴趣的:(java之多线程)