java多线程之API初探(一)

线程创建有两种方式: 
1、实现runnable接口  2、继承thread 线程   都重写run方法
 
2、runnable接口优势:
        java 单继承但可以实现多个接口
        runnable 方式可以实现多线程共享一个公用资源
 
3、线程的生命周期:见下图

 

4、那么sleep 和 wait 是什么?
      用于暂停线程使其他线程获取CUP时间片进行执行
 
  5、各自区别:
      sleep 是 thread 的方法   意义:等待多少毫秒后再唤醒且不会释放对象锁
      wait 是object 方法 需要通过notify 或者 notifyAll 进行唤醒  意义:将该线程挂起释放对象锁
 //以下模拟3个窗口同时售卖5张车票的线程代码。
 //可以说明runnable 接口优势中多线程共享一个公用资源
private int titickits =500000;
     
     public static void main(String[] args) throws InterruptedException {
           Titickits t=new Titickits();
           
           Thread t1=new Thread(t,"窗口A");
           Thread t2=new Thread(t,"窗口B");
           Thread t3=new Thread(t,"窗口C");
           
           t1.start();
           t2.start();
           t3.start();
           t1.wait();
     }

     public  void run() {
           while(titickits>0) {
                titickits--;
                System.out.println(Thread.currentThread().getName()+"剩余"+titickits);
           }
     }

 

posted @ 2018-05-20 13:54  蓝色丶格调  阅读(462)  评论(0编辑  收藏  举报