黑马程序员-java多线程
来源:互联网 发布:淘宝和天猫京东哪个好 编辑:程序博客网 时间:2024/06/05 18:06
---------------------- ASP.Net+Unity开发、.Net培训、期待与您交流! ----------------------
多线程概述:
进程:是一个正在执行中的程序。每一个进程都有一个执行顺序。该顺序是一个执行路径,或者叫一个控制单元。
线程:是进程中的一个独立的控制单元。线程控制着进程的执行。
一个进程中至少有一个线程。
例如,JVM启动时会有一个进程java.exe。该进程中至少有一个线程负责java程序的执行,而且这个线程运行的代码存在于main方法中。该线程称之为主线程。JVM启动了不止一个线程,还包括负责垃圾回收机制的线程等。
多线程的意义:
使多部分代码同时执行;下载时加快速度等。
线程的几种状态:
创建线程方法:
方法一:继承Thread类
方法二:实现Runnable接口
例1:
/***简单的卖票程序,利用多线程实现多个窗口同时卖票*///方法一:继承Thread类class MyThread extends Thread{private static int count=20;public void run(){while(true){if (count>0)System.out.println(Thread.currentThread().getName()+"..."+count--);else break;}}}/*//方法二:实现Runnable接口class Ticket implements Runnable{private int count=20;public void run(){while(true){if(count>0)System.out.println(Thread.currentThread().getName()+"..."+count--);else break;}}}*/class ThreadTest{public static void main(String[] args){Thread t1=new MyThread();Thread t2=new MyThread();t1.start(); //启动线程t2.start();/*Ticket ticket=new Ticket();Thread t3=new Thread(ticket);Thread t4=new Thread(ticket);*/}}
输出结果:
Thread-0...20Thread-0...18Thread-1...19Thread-0...17Thread-1...16Thread-0...15Thread-1...14Thread-0...13Thread-1...12Thread-0...11Thread-1...10Thread-0...9Thread-1...8Thread-0...7Thread-1...6Thread-0...5Thread-1...4Thread-0...3Thread-1...2Thread-0...1此例中,发现运行结果每一次都不同。因为在某一时刻,只能有一个程序在运行(多核CPU除外)。CPU在做着快速的切换,以达到看上去是同时运行的效果。多个线程都在竞争CPU的执行权,CPU执行到谁,谁就运行。因此打印结果并不固定。
两种方法的区别:
实现Runnable接口方法:线程代码存放在接口子类的run方法中。
继承Thread类方法:线程代码存放在Thread子类的run方法中。
实现Runnable接口方法,避免了单继承的局限性。在创建线程时,建议使用实现的方式。
获取线程对象及名称:
线程都有自己默认的名称:Thread-编号,编号从0开始。
static Thread currentThread():获取当前线程对象
getName():获取线程名称
setName()或构造函数:设置线程名称
例2:
/***简单的卖票程序*/class MyThread extends Thread{private static int x;MyThread(String name){super(name);}public void run(){for (x=0;x<10 ;x++ ){System.out.println((Thread.currentThread()==this)+"..."+this.getName()+"run..."+x);}}}class ThreadTest{public static void main(String[] args){Thread t1=new MyThread("线程A");Thread t2=new MyThread("线程B");t1.start(); t2.start();}}
输出结果:
true...线程Arun...0true...线程Arun...1true...线程Brun...0true...线程Arun...2true...线程Brun...3true...线程Arun...4true...线程Brun...5true...线程Arun...6true...线程Brun...7true...线程Arun...8true...线程Brun...9
此例中,我们发现0被打印了两次,因此我们得知多线程运行出现了安全问题。为了解决此问题,需要了解多线程的同步知识。
多线程的安全问题:
例3:
/***简单的卖票程序,利用多线程实现多个窗口同时卖票*/class Ticket implements Runnable{private int count=20;public void run(){while(true){if(count>0){try{Thread.sleep(10);}catch(Exception e){}System.out.println(Thread.currentThread().getName()+"...sale"+count--);}else break;}}}class ThreadTest{public static void main(String[] args){Ticket ticket=new Ticket();Thread t3=new Thread(ticket);Thread t4=new Thread(ticket);t3.start();t4.start();}}
输出结果:
Thread-0...sale20Thread-1...sale19Thread-1...sale18Thread-0...sale17Thread-0...sale16Thread-1...sale15Thread-1...sale14Thread-0...sale13Thread-1...sale12Thread-0...sale11Thread-0...sale10Thread-1...sale9Thread-0...sale8Thread-1...sale7Thread-0...sale6Thread-1...sale5Thread-0...sale4Thread-1...sale3Thread-0...sale2Thread-1...sale1Thread-0...sale0
此例中,Thread-0售出了第0张票,而这是错票。与例2一样,多线程的运行出现了安全问题。
问题的原因:当多条语句在操作同一个线程共性数据时,一个线程对多条语句只执行了一部分,还没有执行完时,另一个线程参与进来执行,导致共性数据的错误。
解决办法:对多条操作共性数据的语句,只让一个线程执行完。在执行过程中,其他线程不可以参与执行。
java对于多线程的安全问题提供了专业的解决方式:同步代码块或同步函数
同步代码块:
synchronized(对象){ 需要被同步的代码}
同步函数:
[访问修饰符] synchronized [返回值类型] function(参数列表){}同步的意义:
对象如同锁,持有锁的线程可以在同步中执行。没有持有锁的线程即使获取CPU的执行权,也进不去,因为没有获取锁。
使用同步时的注意事项:
1、明确哪些代码是多线程运行代码;
2、明确共享数据;
3、明确多线程运行代码中哪些语句是操作共享数据的。
总而言之,只需要同步需要同步的语句。
例4:利用同步代码块解决例3中暴露的安全问题
/***简单的卖票程序,利用多线程实现多个窗口同时卖票*/class Ticket implements Runnable{private int count=20;//不用staticObject obj=new Object();public void run(){while(true){synchronized(obj) //同步代码块,同步操作共享数据的语句{if(count>0){try{Thread.sleep(10);}catch(Exception e){}System.out.println(Thread.currentThread().getName()+"..."+count--);}else break;}}}}
输出结果:
Thread-0...20Thread-0...19Thread-0...18Thread-0...17Thread-0...16Thread-0...15Thread-0...14Thread-0...13Thread-0...12Thread-0...11Thread-0...10Thread-1...9Thread-1...8Thread-1...7Thread-1...6Thread-1...5Thread-1...4Thread-1...3Thread-1...2Thread-1...1
同步函数使用的锁是this:
同步函数用的是哪一个锁那?函数需要被对象调用,那么函数都有一个所属对象引用,就是this。所以同步函数使用的锁是this。
我们通过例5来进行验证。
例5:
/***使用两个线程来卖票,一个线程在同步代码块中,一个线程在同步函数中,都在执行卖票动作*/class Ticket implements Runnable{private int count=100;//不用staticboolean flag=true;public void run(){if(flag){while(true){synchronized(this) //同步代码块以this为锁{if(count>0){try{Thread.sleep(10);}catch(Exception e){}System.out.println(Thread.currentThread().getName()+"...code..."+count--);}else break;}}}elsewhile(true)show();}public synchronized void show(){if(count>0){try{Thread.sleep(10);}catch(Exception e){}System.out.println(Thread.currentThread().getName()+"...show..."+count--);}}}class ThreadTest{public static void main(String[] args){Ticket ticket=new Ticket();Thread t3=new Thread(ticket);Thread t4=new Thread(ticket);t3.start();try{Thread.sleep(10);}catch(Exception e){}ticket.flag=false;t4.start();}}
打印结果过长,请读者自己验证。此例结果显示,多线程未出现安全问题,说明同步成功,证明了同步函数的锁是this。
静态同步函数的锁是Class对象:
如果同步函数被静态修饰后,使用的锁是什么呢?
通过类似例5的验证,发现不是this,因为静态方法中不可以定义this。类进入内存时,内存中没有本类对象,但是一定有该类对应的字节码文件对象,即类名.class。
静态的同步方法,使用的锁是该方法所在类的字节码文件对象。
死锁:
同步中嵌套同步。当两个线程被阻塞,每个线程在等待另一个线程时就发生死锁。如例6,
例6:
/***使用两个线程来卖票,一个线程在同步代码块中,一个线程在同步函数中,都在执行卖票动作*/class Ticket implements Runnable{private int count=100;//不用staticObject obj=new Object();boolean flag=true;public void run(){if(flag){while(true){synchronized(obj) //同步代码块以this为锁{show();}}}elsewhile(true)show();}public synchronized void show(){synchronized(obj){if(count>0){try{Thread.sleep(10);}catch(Exception e){}System.out.println(Thread.currentThread().getName()+"...show..."+count--);}}}}class ThreadTest{public static void main(String[] args){Ticket ticket=new Ticket();Thread t3=new Thread(ticket);Thread t4=new Thread(ticket);t3.start();try{Thread.sleep(10);}catch(Exception e){}ticket.flag=false;t4.start();}}
线程间通信:
其实就是多个线程在操作同一个资源,但是操作的动作不同。
例7:
//线程间通讯,输入与输出案例class Resource{public boolean flag=false;public String name;public String sex;}class Input implements Runnable{private Resource r;Input(Resource r){this.r=r;}public void run(){int x=0;while (true){synchronized(r){if(x==0){r.name="AAA";r.sex="male";}else{r.name="BBB";r.sex="female";}x=(x+1)%2;}}}}class Output implements Runnable{private Resource r;Output(Resource r){this.r=r;}public void run(){while(true){synchronized(r){System.out.println(r.name+"...."+r.sex);}}}}class ThreadTest{public static void main(String[] args){Resource r=new Resource();new Thread(new Input(r)).start();new Thread(new Output(r)).start();}}
输出结果:
BBB....femaleBBB....femaleBBB....femaleBBB....femaleBBB....femaleBBB....femaleAAA....maleAAA....maleAAA....male
由于例7中,未设置跳出循环语句,所以结果将不断打印下去。这里只是截取了开头部分。由此我们可以发现,虽然同步代码块解决了输入、输出同时进行造成的安全隐患,但是仍存在连续输入或连续输出的情况,而我们希望输入、输出依次进行。而这需要引入等待唤醒机制。
等待唤醒机制需要从java.lang.Object的类的三个方法来学习:
void notify():唤醒在此对象监视器上等待的单个线程。
void notifyAll():唤醒在此对象监视器上等待的所有线程。
void wait():导致当前的线程等待,直到其他线程调用此对象的notify()方法或notifyAll()方法。
例8:
//线程间通讯,输入与输出案例//通过等待唤醒机制,使输入、输出依次进行class Resource{public boolean flag=false;public String name;public String sex;}class Input implements Runnable{private Resource r;Input(Resource r){this.r=r;}public void run(){int x=0;while (true){synchronized(r){if(r.flag)try{r.wait();}catch(Exception e){} //使输入线程等待if(x==0){r.name="AAA";r.sex="male";}else{r.name="BBB";r.sex="female";}x=(x+1)%2;r.flag=true;r.notify(); //唤醒监视器中等待的线程}}}}class Output implements Runnable{private Resource r;Output(Resource r){this.r=r;}public void run(){while(true){synchronized(r){if(!r.flag)try{r.wait();}catch(Exception e){}System.out.println(r.name+"...."+r.sex);r.flag=false;r.notify();}}}}class ThreadTest{public static void main(String[] args){Resource r=new Resource();new Thread(new Input(r)).start();new Thread(new Output(r)).start();}}
输出结果:
AAA....maleBBB....femaleAAA....maleBBB....femaleAAA....maleBBB....femaleAAA....maleBBB....femaleAAA....maleBBB....femaleAAA....maleBBB....femaleAAA....maleBBB....femaleAAA....maleBBB....femaleAAA....maleBBB....female由于例8中,未设置跳出循环语句,所以结果将不断打印下去。这里只是截取了开头部分。
由结果可知,等待唤醒机制的引入很好的解决了例7的问题。
例9:代码优化
//输入、输出案例的优化class Resource {private boolean flag=false;private String name;private String sex;public synchronized void setR(String name,String sex){if(flag)try{this.wait();}catch(Exception e){}this.name=name;this.sex=sex;flag=true;this.notify();}public synchronized void getR(){if(!flag)try{this.wait();}catch(Exception e){}System.out.println(name+"..."+sex);flag=false;this.notify();}}class Input implements Runnable{private Resource r;Input(Resource r){this.r=r;}public void run(){int x=0;while(true){if(x==0)r.setR("AAA","male");elser.setR("BBB","female");x=(1+x)%2;}}}class Output implements Runnable{private Resource r;Output(Resource r){this.r=r;}public void run(){while (true){r.getR();}}}class ThreadTest{public static void main(String[] args){Resource r=new Resource();new Thread(new Input(r)).start();new Thread(new Output(r)).start();}}
例10:生成者与消费者案例
class Resource {private boolean flag=false;private String name;public synchronized void setR(String name){if(flag)try{this.wait();}catch(Exception e){}this.name=name;System.out.println(Thread.currentThread().getName()+"输入..."+this.name);flag=true;this.notify();}public synchronized void getR(){if(!flag)try{this.wait();}catch(Exception e){}System.out.println(Thread.currentThread().getName()+"输出..."+this.name);flag=false;this.notify();}}class Input implements Runnable{private Resource r;Input(Resource r){this.r=r;}public void run(){while(true){r.setR("商品");}}}class Output implements Runnable{private Resource r;Output(Resource r){this.r=r;}public void run(){while (true){r.getR();}}}class ThreadTest{public static void main(String[] args){Resource r=new Resource();new Thread(new Input(r)).start();new Thread(new Output(r)).start();new Thread(new Input(r)).start();new Thread(new Output(r)).start();new Thread(new Input(r)).start();new Thread(new Output(r)).start();}}
输出结果:
Thread-0输入...商品Thread-1输出...商品Thread-0输入...商品Thread-1输出...商品Thread-0输入...商品Thread-2输入...商品Thread-1输出...商品Thread-0输入...商品Thread-3输出...商品Thread-2输入...商品Thread-0输入...商品Thread-3输出...商品Thread-2输入...商品Thread-5输出...商品Thread-0输入...商品由于例10中,未设置跳出循环语句,所以结果将不断打印下去。这里只是截取了开头部分。
由结果可知,当输入、输出线程分别多个时,无法保证输入、输出依次进行。
解决办法:把用if语句来判断标记,改为用while语句判断标记。
例11:
将例10中setR()、getR()方法修改如下:
public synchronized void setR(String name){while(flag)try{this.wait();}catch(Exception e){}this.name=name;System.out.println(Thread.currentThread().getName()+"输入..."+this.name);flag=true;this.notify();}public synchronized void getR(){while(!flag)try{this.wait();}catch(Exception e){}System.out.println(Thread.currentThread().getName()+"输出..."+this.name);flag=false;this.notify();}
输出结果:
发现程序会陷入等待。因为只用notify(),容易只唤醒本方线程的情况,导致程序中的所有线程都等待。
解决办法:将notify()方法改为notifyAll()方法。
例12:将例10中setR()、getR()方法修改如下:
public synchronized void setR(String name){while(flag)try{this.wait();}catch(Exception e){}this.name=name;System.out.println(Thread.currentThread().getName()+"输入..."+this.name);flag=true;this.notifyAll();}public synchronized void getR(){while(!flag)try{this.wait();}catch(Exception e){}System.out.println(Thread.currentThread().getName()+"输出..."+this.name);flag=false;this.notifyAll();}
输出结果:
Thread-0输入...商品Thread-1输出...商品Thread-0输入...商品Thread-1输出...商品Thread-0输入...商品Thread-1输出...商品Thread-0输入...商品Thread-1输出...商品Thread-0输入...商品Thread-3输出...商品由于例12中,未设置跳出循环语句,所以结果将不断打印下去。这里只是截取了开头部分。
由结果可知,例12很好的解决了例10的问题。
java1.5升级后的新特性:
JDK1.5中提供了多线程升级解决方案。
将同步synchronized替换成现实Lock操作;将对象锁替换成Condition对象,它可以通过Lock锁获得;将对象锁的wait()、notify()、notifyAll()方法替换成Condition对象的await()、signal()、signalAll()方法。
在例13中,实现本方只唤醒对方的操作,
例13:多线程升级解决方案
import java.util.concurrent.locks.*;class Resource {private boolean flag=false;private String name;private Lock lock=new ReentrantLock(); //获取Lock对象private Condition condition_pro=lock.newCondition();//获取生产者conditionprivate Condition condition_con=lock.newCondition();//获取消费者conditionpublic void setR(String name)throws InterruptedException{lock.lock();try{while(flag)condition_pro.await();this.name=name;System.out.println(Thread.currentThread().getName()+"输入..."+this.name);flag=true;condition_con.signal();}finally{lock.unlock();}}public void getR()throws InterruptedException{lock.lock();try{while(!flag)condition_con.await();System.out.println(Thread.currentThread().getName()+"输出..."+this.name);flag=false;condition_pro.signal();}finally{lock.unlock();}}}class Input implements Runnable{private Resource r;Input(Resource r){this.r=r;}public void run(){while(true){try{r.setR("商品");}catch (Exception e){}}}}class Output implements Runnable{private Resource r;Output(Resource r){this.r=r;}public void run(){while (true){try{r.getR();}catch (Exception e){}}}}class ThreadTest{public static void main(String[] args){Resource r=new Resource();new Thread(new Input(r)).start();new Thread(new Output(r)).start();new Thread(new Input(r)).start();new Thread(new Output(r)).start();new Thread(new Input(r)).start();new Thread(new Output(r)).start();}}
用升级解决方案重写例12,效果相同。
停止线程:
stop()方法已经过时,那么如何停止线程?
只有一种,那就是run()方法结束。开启多线程运行,运行代码通常是循环结构,因此只要控制住循环,就可以让run()方法结束,也就是线程停止。
例14:
class StopThread implements Runnable{private boolean flag=true;public void run(){while(flag){System.out.println(Thread.currentThread().getName()+"...run");}}public void changeFlag(){flag=false;}}class ThreadTest{public static void main(String[] args){StopThread st=new StopThread();Thread t1=new Thread(st);t1.start();int num=0;while (true){if (num++==10){st.changeFlag();break;}System.out.println(Thread.currentThread().getName()+"..."+num);}System.out.println("OVER!");}}
输出结果:
main...1Thread-0...runThread-0...runmain...2Thread-0...runmain...3Thread-0...runmain...4Thread-0...runmain...5Thread-0...runmain...6Thread-0...runmain...7main...8main...9Thread-0...runmain...10Thread-0...runOVER!
由结果可知,线程t1可以结束。
特殊情况:
当线程处于冻结状态,就不会读取到标记,那么线程就不会结束。
当没有指定的方式让冻结的线程恢复到运行状态时,需要对冻结状态进行清除,强制让线程恢复到运行状态中来,这样就可以操作标记让线程结束。
例14:
class StopThread implements Runnable{private boolean flag=true;public synchronized void run(){while(flag){try{wait();}catch (InterruptedException e){System.out.println(Thread.currentThread().getName()+"...Exception");flag=false;}System.out.println(Thread.currentThread().getName()+"...run");}}public void changeFlag(){flag=false;}}class ThreadTest{public static void main(String[] args){StopThread st=new StopThread();Thread t1=new Thread(st);t1.start();int num=0;while (true){if (num++==10){t1.interrupt();//强制让线程t1恢复到运行状态中break;}System.out.println(Thread.currentThread().getName()+"..."+num);}System.out.println("OVER!");}}
输出结果:
main...1main...2main...3main...4main...5main...6main...7main...8main...9main...10OVER!Thread-0...ExceptionThread-0...run
守护线程:
即后台线程,前台线程结束后,后台自动结束。
setDaemon():将线程设置为守护线程。
线程调度:
join()方法:
当A线程执行到B线程的.join()方法时,A就会等待。直到B线程都执行完,A才会继续执行。
join()可以用来临时加入线程执行。
例15:
public static void main(String[] args){Demo d=new Demo();Thread t1=new Thread(d);Thread t2=new Thread(d);t1.start();t2.start();t1.join();System.out.println("OVER!");}当main方法执行到t1.join()时,main方法就会等待,直到t1线程执行完,main方法才会继续执行,打印“OVER”。
yield()方法:
临时释放线程执行权,减缓线程执行频率。
优先级:
默认为5,常用1,5,10。
setPriority():设定线程的优先级。
MAX_PRIORITY=10;MIN_PRIORITY=1;NORM_PRIORITY=5;
开发常见写法:
class ThreadTest{public static void main(String[] args){new Thread(){public void run(){for (int x=0;x<10 ;x++ ){System.out.println(Thread.currentThread().getName()+"Thread..."+x);}}}.start();for (int x=0;x<10 ;x++ ){System.out.println(Thread.currentThread().getName()+"main..."+x);}Runnable r=new Runnable(){public void run(){for (int x=0;x<10 ;x++ ){System.out.println(Thread.currentThread().getName()+"Runnable..."+x);}}};new Thread(r).start();}}
延伸阅读:
java多线程编程总结
---------------------- ASP.Net+Unity开发、.Net培训、期待与您交流! ----------------------详细请查看:www.itheima.com
- 黑马程序员-java多线程
- 黑马程序员--java 多线程
- 黑马程序员-java多线程
- 黑马程序员--Java多线程
- 黑马程序员--java多线程
- 黑马程序员:Java多线程
- 黑马程序员 Java多线程
- 黑马程序员---Java多线程
- 黑马程序员---多线程【java】
- 黑马程序员----JAVA----多线程---
- 黑马程序员-java多线程
- 黑马程序员-java 多线程
- 黑马程序员-------Java多线程
- 黑马程序员-java多线程
- 黑马程序员-Java多线程
- 黑马程序员 java 多线程
- 黑马程序员--java多线程
- 黑马程序员-java多线程
- 【C语言复习(二十六)】各个目标文件的关系
- 迭代器 与泛型for
- scala入门2(简介与基础语法2--数值类型)
- XML解析之DOM4J
- UITableView(二编辑删除)
- 黑马程序员-java多线程
- maven中央仓库地址,什么jar包多可以搜到
- 未能加载类型
- 如何将Sql server数据库中的模型图转化到Word中--并能够查看字段的属性信息
- XtraBackup备份原理图解
- 视频面试
- ARM处理器学习之--GPIO操作篇(gnu link script)
- 快速掌握一个语言最常用的50%
- WCF 测试简介