Java 多线程

Java 多线程

1、 使用join方法可以让一个线程强制执行,线程强制执行的时候其它线程无法运行,必须等待该线程运行完毕后才可以继续运行;
2、 Sysnchronized 同步锁

package com.dt.java.test;

public class JavaThead {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  TicketLogicThread saleTicket =new TicketLogicThread();
        Thread t1=new Thread(saleTicket) ;
        Thread t2=new Thread(saleTicket) ;
        Thread t3=new Thread(saleTicket) ;
        Thread t4=new Thread(saleTicket) ;
        Thread t5=new Thread(saleTicket) ;
        t1.start();
        System.out.println("getName     "+t1.getName());
        t2.start();
        t3.start();
        t4.start();
        t5.start();
        System.out.println("getName     "+t5.getName());
       
  /*
      new HelloThread().start();
  Thread thread1 = new HelloThread();
  thread1.start();
  thread1.interrupt();
  
       new Thread(new Runnable(){
        public void run(){
       for(int i =0; i <5; i++){
        System.out.println(i);
        }
       }
 }).start();
       new Thread(new MyLogic()).start();
     
       Thread thread = new Thread(new MyLogic());
       thread.start();
         
       try {
  thread.join();
 } catch (InterruptedException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 }
      
      
      
       System.out.println(thread.getName());
       System.out.println("getName     "+thread.currentThread().getName());
       System.out.println("thread.getPriority is   "+thread.getPriority());
      
        */
       
 }
}


class HelloThread extends Thread { //定义线程
 public void run(){ //线程运行时run被调用
  for(int i =0; i <5; i++){
   System.out.println(i);
            if(3 == i){
    interrupt();
   }
  }
 }
  }


class MyLogic implements Runnable{
 
   @Override
   public void run() {
 // TODO Auto-generated method stub
  System.out.println("MyLogic");
  for(int i =0; i <5; i++){
   try {
    Thread.sleep(1000);
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   System.out.println(i);
   
   
  }
 }
}

 


class TicketLogicThread implements Runnable{ //买票的例子
   private int ticket =5;
 @Override
 public void run() {
  // TODO Auto-generated method stub
  for (int  i =0; i<5; i++){
   sale();
    
   }
  }
 
 public synchronized void sale(){
  if (ticket >0){
   try {
    Thread.sleep(500);
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   
   
   System.out.println("Ticket ID:  "+ ticket--);

  }
 }
 
}


运行结果
getName     Thread-0
getName     Thread-4
Ticket ID:  5
Ticket ID:  4
Ticket ID:  3
Ticket ID:  2
Ticket ID:  1


 

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