黑马程序员__多线程

------<a href="http://www.itheima.com" target="blank">Java培训、Android培训、iOS培训、.Net培训</a>、期待与您交流! -------


1.线程是程序执行的一条路径, 一个进程中可以包含多条线程,多线程并发执行可以提高程序的效率, 可以同时完成多项工作。

2.开启新线程的两种方式
 1).继承Thread

[java]  view plain copy
  1. public static void main(String[] args) {  
  2.     MyThread mt = new MyThread();       //4,创建自定义类对象  
  3.     mt.start();             <span style="font-family:宋体;">//5,开启线程  
  4. </span>   for(int i = 0; i < 10000; i++) {  
  5.     System.out.println("传智播客");  
  6.         }  
  7.     }  
  8.   
  9. }  
  10.   
  11. class MyThread extends Thread {                     //1,自定义类继承Thread  
  12.     public void run() {                     //2,重写run方法  
  13.         for(int i = 0; i < 10000; i++) { //3,将要执行的代码写在run方法中  
  14.             System.out.println("黑马程序员");  
  15.         }  
  16.     }  
  17. }  


 2).实现Runnable

[java]  view plain copy
  1. public static void main(String[] args) {  
  2.         MyRunnable mr = new MyRunnable();//4,创建自定义类对象  
  3.         Thread t = new Thread(mr);   //5,将自定义类对象当作参数传递给Thread的构造函数    
  4.         t.start();           //6,开启线程  
  5.           
  6.         for(int i = 0; i < 10000; i++) {  
  7.             System.out.println("传智播客");  
  8.         }  
  9.     }  
  10.   
  11. }  
  12.   
  13. class MyRunnable implements Runnable {      //1,自定义类实现Runnable接口  
  14.   
  15.     @Override  
  16.     public void run() {         //2,重写run方法  
  17.         for(int i = 0; i < 10000; i++) {//3,将要执行的代码写在run方法中  
  18.             System.out.println("黑马程序员");  
  19.         }  
  20.     }  
  21. }  

3.Thread类常用方法
 获取名字: getName()方法
 设置名字:通过构造函数可以传入String类型的名字或通过setName(String)方法可以设置线程对象的名字
 获取当前线程对象:Thread.currentThread()
 休眠:Thread.sleep(毫秒,纳秒)
 守护:setDaemon()
 加入:

   join(), 当前线程暂停, 等待指定的线程执行结束后, 当前线程再继续
    join(int), 可以等待指定的毫秒之后继续

 让出cpu:yield
 设置线程的优先级:setPriority()

[java]  view plain copy
  1. public static void main(String[] args) {  
  2.         final Thread t1 = new Thread() {  
  3.             public void run() {  
  4.                 for(int i = 0; i < 50; i++) {  
  5.                     try {  
  6.                         Thread.sleep(10);//休眠  
  7.                     } catch (InterruptedException e) {  
  8.                         // TODO Auto-generated catch block  
  9.                         e.printStackTrace();  
  10.                     }  
  11.                     System.out.println(getName() + "...传智播客");  
  12.                 }  
  13.             }  
  14.         };  
  15.           
  16.         Thread t2 = new Thread(new Runnable(){  
  17.             public void run() {  
  18.                 for(int i = 0; i < 50; i++) {  
  19.                     if(i == 2) {  
  20.                     try {  
  21.                     //t1.join();//让出cpu,只有t1完全执行完,再执行t2  
  22.                     t1.join(1);//让出cpu,但是只让出1毫秒,就是指定参数的时间  
  23.                     } catch (InterruptedException e) {  
  24.                               
  25.                         e.printStackTrace();  
  26.                     }  
  27.                     }  
  28.             System.out.println(Thread.currentThread().getName() + "...黑马程序员");  
  29.                 } //获取当前线程对象  
  30.             }  
  31.         });  
  32.         t1.setDaemon(true); //设置t1为守护线程  
  33.         t1.start();  
  34.         t2.start();  
  35.     }  


4.线程之间的同步

 线程之间的同步有同步代码块和同步方法

 同步代码块是使用synchronized关键字加上一个锁对象来定义一段代码,多个同步代码块使用相同的锁对象
 同步方法是使用synchronized关键字修饰一个方法, 该方法中所有的代码都是同步的,非静态同步方法默认使用当 前对象this作为锁对象,静态方同步函数的锁是该类的字节码对象。字节码对象可以认为是万能锁。

 要注意的是多线程同步的时候, 如果同步代码嵌套, 使用相同锁, 就有可能出现死锁,所以尽可能不要嵌套使用。

例如:模拟售票,总数为一千张,有四个窗口卖票:


[java]  view plain copy
  1. public class Ticket {  
  2.     public static void main(String[] args) {  
  3.         new TicketsSeller().start();    //开启线程  
  4.         new TicketsSeller().start();  
  5.         new TicketsSeller().start();  
  6.         new TicketsSeller().start();  
  7.     }  
  8.   
  9. }  
  10.   
  11. class TicketsSeller extends Thread {  
  12.     private static int tickets = 1000;  
  13.     public void run() {  
  14.         while(true) {  
  15.             synchronized(TicketsSeller.class) {  
  16.                 if(tickets == 0)      
  17.                     break;    
  18.                 try {  
  19.                     Thread.sleep(10);//增强效果  
  20.                 } catch (InterruptedException e) {  
  21.                     e.printStackTrace();  
  22.                 }  
  23.                 System.out.println(getName() + "...这是第" + tickets-- + "号票");//卖票,并将结果--  
  24.             }  
  25.         }  
  26.     }  
  27. }  

5.单例设计模式

单例设计模式:保证类在内存中只有一个对象。
 (1)将构造方法私有。
 (2)在本类中定义一个本类的对象。Singleton s;
 (3)提供公共的访问方式。public static Singleton getInstance(){return s}

 单例写法两种:饿汉式,懒汉式;

饿汉式:

[java]  view plain copy
  1. class Singleton{  
  2.     private Singleton(){}  
  3.     private static Singleton s=new Singleton();  
  4.     public static Singleton getInstance(){  
  5.             return s;  
  6.       }  
  7. }  

懒汉式:

[java]  view plain copy
  1. class Singleton{  
  2.         private Sinleton(){}  
  3.         private static Singleton s;  
  4.         public static Sinleton getInstance(){  
  5.              if(s==null){  
  6.                 s=new Sinleton();}  
  7.                 return s;  
  8.           }  
  9. }  


第三种格式:

[java]  view plain copy
  1. class Singleton {  
  2.         private Singleton() {}  
  3.   
  4.         public static final Singleton s = new Singleton();//final是最终的意思,被final修饰的变量不可以被更改  
  5.     }  


6.线程之间的通信
  线程等待, wait()
  唤醒等待  notify();
  这两个方法必须在同步代码中执行, 并且使用同步锁对象来调用
  多个线程通信的问题
  notify()方法是随机唤醒一个线程
  notifyAll()方法是唤醒所有线程
  JDK5之前无法唤醒指定的一个线程
  如果多个线程之间通信, 需要使用notifyAll()通知所有线程, 用while来反复判断条件

[java]  view plain copy
  1. public class Demo6_Notify {  
  2.     public static void main(String[] args) {  
  3.         final Printer p = new Printer();  
  4.         new Thread() {  
  5.             public void run() {  
  6.                 while(true) {  
  7.                     try {  
  8.                         p.print1();  
  9.                     } catch (InterruptedException e) {  
  10.                           
  11.                         e.printStackTrace();  
  12.                     }  
  13.                 }  
  14.             }  
  15.         }.start();  
  16.           
  17.         new Thread() {  
  18.             public void run() {  
  19.                 while(true) {  
  20.                     try {  
  21.                         p.print2();  
  22.                     } catch (InterruptedException e) {  
  23.                           
  24.                         e.printStackTrace();  
  25.                     }  
  26.                 }  
  27.             }  
  28.         }.start();  
  29.     }  
  30.   
  31. }  
  32.   
  33. class Printer {  
  34.     private int flag = 1;  
  35.     public void print1() throws InterruptedException {  
  36.         synchronized(this){  
  37.             if(flag != 1)  
  38.                 this.wait();                            //线程等待  
  39.             System.out.print("传");  
  40.             System.out.print("智");  
  41.             System.out.print("播");  
  42.             System.out.print("客");  
  43.             System.out.print("\r\n");  
  44.             flag = 2;                               //flag改为2  
  45.             this.notify();                              //唤醒等待的线程  
  46.         }  
  47.     }  
  48.       
  49.     public void print2() throws InterruptedException {  
  50.         synchronized(this){  
  51.             if(flag != 2)   
  52.                 this.wait();                            //线程等待  
  53.               
  54.             System.out.print("黑");  
  55.             System.out.print("马");  
  56.             System.out.print("程");  
  57.             System.out.print("序");  
  58.             System.out.print("员");  
  59.             System.out.print("\r\n");  
  60.             flag = 1;                               //flag改为1  
  61.             this.notify();                              //唤醒等待的线程  
  62.         }  
  63.     }  


7.JDK5之后的线程控制
 同步
  使用ReentrantLock类的lock()和unlock()方法进行同步
 通信
  使用ReentrantLock类的newCondition()方法可以获取Condition对象
  需要等待的时候使用Condition的await()方法, 唤醒的时候用signal()方法
  不同的线程使用不同的Condition, 这样就能区分唤醒的时候找哪个线程了

[java]  view plain copy
  1. package cn.itcast.thread;  
  2.   
  3. import java.util.concurrent.locks.Condition;  
  4. import java.util.concurrent.locks.ReentrantLock;  
  5.   
  6. public class Demo8_ReentrantLock{  
  7.     public static void main(String[] args) {  
  8.         final Printer3 p = new Printer3();  
  9.         new Thread() {  
  10.             public void run() {  
  11.                 while(true) {  
  12.                     try {  
  13.                         p.print1();  
  14.                     } catch (InterruptedException e) {  
  15.                           
  16.                         e.printStackTrace();  
  17.                     }  
  18.                 }  
  19.             }  
  20.         }.start();  
  21.           
  22.         new Thread() {  
  23.             public void run() {  
  24.                 while(true) {  
  25.                     try {  
  26.                         p.print2();  
  27.                     } catch (InterruptedException e) {  
  28.                           
  29.                         e.printStackTrace();  
  30.                     }  
  31.                 }  
  32.             }  
  33.         }.start();  
  34.           
  35.         new Thread() {  
  36.             public void run() {  
  37.                 while(true) {  
  38.                     try {  
  39.                         p.print3();  
  40.                     } catch (InterruptedException e) {  
  41.                           
  42.                         e.printStackTrace();  
  43.                     }  
  44.                 }  
  45.             }  
  46.         }.start();  
  47.     }  
  48.   
  49. }  
  50.   
  51. class Printer3 {  
  52.     private ReentrantLock r = new ReentrantLock();          //创建锁对象  
  53.     private Condition c1 = r.newCondition();                //添加监视器  
  54.     private Condition c2 = r.newCondition();  
  55.     private Condition c3 = r.newCondition();  
  56.     private int flag = 1;  
  57.     public void print1() throws InterruptedException {  
  58.         r.lock();                       //获取锁  
  59.             if(flag != 1)  
  60.                 c1.await();             //线程等待  
  61.             System.out.print("传");  
  62.             System.out.print("智");  
  63.             System.out.print("播");  
  64.             System.out.print("客");  
  65.             System.out.print("\r\n");  
  66.             flag = 2;                       //flag改为2  
  67.             c2.signal();                    //唤醒线程2  
  68.         r.unlock();                     //释放锁  
  69.     }  
  70.       
  71.     public void print2() throws InterruptedException {  
  72.         r.lock();                       //获取锁  
  73.             if(flag != 2) {  
  74.                 c2.await();             //线程等待,2线程等待  
  75.             }  
  76.             System.out.print("黑");  
  77.             System.out.print("马");  
  78.             System.out.print("程");  
  79.             System.out.print("序");  
  80.             System.out.print("员");  
  81.             System.out.print("\r\n");  
  82.             flag = 3;                   //flag改为3  
  83.             c3.signal();                    //唤醒线程3  
  84.         r.unlock();                     //释放锁  
  85.     }  
  86.       
  87.     public void print3() throws InterruptedException {  
  88.         r.lock();                       //获取锁  
  89.             if(flag != 3) {  
  90.                 c3.await();             //线程等待,3线程等待  
  91.             }  
  92.             System.out.print("i");  
  93.             System.out.print("t");  
  94.             System.out.print("c");  
  95.             System.out.print("a");  
  96.             System.out.print("s");  
  97.             System.out.print("t");  
  98.             System.out.print("\r\n");  
  99.             flag = 1;                   //flag改为1  
  100.             c1.signal();                    //唤醒线程1  
  101.         r.unlock();                     //释放锁  
  102.     }  
  103. }  
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值