多线程总结

一、 了解进程和线程

       在多任务系统中,每个独立执行的程序称为进程,也就是“正在进行的程序”。我们现在使用的操作系统一般都是多任务的,既能够同时执行多个应用程序,实际情况是,操作系统负责对cpu等设备的资源进行分配和管理,虽然这些设备某一时刻只能做一件事,但以非常小的时间间隔交替执行多个程序,就可以给人以同时执行多个程序的感觉。

          一个进程中又可以包含一个或多个线程,一个线程就是一个程序内部的一条执行线索,如果一程序中实现多段代码同时交替运行,就需要产生多个线程,并指定每个线程上所要运行的程序代码段,这就是多线程

          1.程与单线程的对比:                  

 

       比如以下这段代码是单线程的,执行的结果是run():main,它只会执行run()方法,当run方法执行完后才会执行main后面的方法

  1. class ThreadDemo1  
  2. {  
  3.     public static void main(String [] args)  
  4.     {  
  5.         new TestThread().run();  
  6.         while(true)  
  7.         {  
  8.             //打印当前线程的名称  
  9.             System.out.println("main():"+Thread.currentThread().getName());  
  10.         }  
  11.     }  
  12. }  
  13. class TestThread  
  14. {  
  15.     public void run()  
  16.     {  
  17.         while(true)  
  18.         {  
  19.             System.out.println("run():"+Thread.currentThread().getName());  
  20.         }  
  21.     }  
  22. }  

     以下这段代码是多线程的,执行的结果是run():Thread-0;和mainThread-0交替执行,实现多线程首先要继承Thread这个类,覆盖run方法,然后new这个子类调用它的start方法就可以创建出多线程。

  1. class ThreadDemo1  
  2. {  
  3.     public static void main(String [] args)  
  4.     {  
  5.         new TestThread().start();  
  6.         while(true)  
  7.         {  
  8.             System.out.println("main():"+Thread.currentThread().getName());  
  9.         }  
  10.     }  
  11. }  
  12. class TestThread extends Thread  
  13. {  
  14.     public void run()  
  15.     {  
  16.         while(true)  
  17.         {  
  18.             System.out.println("run():"+Thread.currentThread().getName());  
  19.         }  
  20.     }  
  21. }  

二、 用Thread类创建线程

       要讲一段代码在一个新的线程上运行,该代码应该在一个类的run函数中,并且run函数所在的类是Thread类的子类。倒过来看,我们要实现多线程,必须编写一个继承Thread类的子类,子类要覆盖Thread类中的run函数,在子类的run函数中调用想在新线程上运行的程序代码。

          启动一个新的线程,我们不是直接调用Thread的子类对象的run方法,而是调用Thread的子类对象的start(从Thread类继承到的)方法,Thread类对象的的start方法将产生 一个新的线程,并在该线程上运行该Thread类对象中的run方法,根据面向对象运行时的多态性,在该线程上实际运行的是Thread子类对象中的run方法

       由于线程的代码段在run方法中,那么该方法执行完成以后,线程也就向应得结束了,因而我们可以通过控制run方法中循环条件来控制线程的结束。

 

三、 后台线程与联合线程

          如果我们对某个线程对象在启动(调用start方法)之前调用了setDaemon(true)方法,这个线程就变成了后台线程。反之如果我们没有调用setDaemon或setDaemon传递为false,则这个线程为前台线程。

      1.线程和后台线程的区别:

 

  1. class ThreadDemo1  
  2. {  
  3.     public static void main(String [] args)  
  4.     {  
  5.         new TestThread().start();  
  6.         /*while(true)  
  7.         {  
  8.             System.out.println("main():"+Thread.currentThread().getName());  
  9.         }*/  
  10.     }  
  11. }  
  12. class TestThread extends Thread  
  13. {  
  14.     public void run()  
  15.     {  
  16.         while(true)  
  17.         {  
  18.             System.out.println("run():"+Thread.currentThread().getName());  
  19.         }  
  20.     }  
  21. }  

这是一个前台线程,主线程结束了,而java线程并没有结束,对java程序来说只要还有一个前台线程在运行,整个进程都不会结束

  1. class ThreadDemo1  
  2. {  
  3.     public static void main(String [] args)  
  4.     {  
  5.         //new TestThread().start();  
  6.         Thread tt =new TestThread();  
  7.         tt.setDaemon(true);  
  8.         tt.start();  
  9.         /*while(true)  
  10.         {  
  11.             System.out.println("main():"+Thread.currentThread().getName());  
  12.         }*/  
  13.     }  
  14. }  
  15. class TestThread extends Thread  
  16. {  
  17.     public void run()  
  18.     {  
  19.         while(true)  
  20.         {  
  21.             System.out.println("run():"+Thread.currentThread().getName());  
  22.         }  
  23.     }  
  24. }  

这是一个后台线程,这段程序说明了只有后台线程在运行,没有前台线程了,那么整个java进程很快就会结束

也就是说对java程序来说,只要还有一个前台线程在运行,这个进程就不会结束,如果一个进程中只有后台线程在运行,这个进程就会结束

      我们如何调用线程对象的join()方法,将一个线程合并到另外一个线程中去:

 

  1. <span style="font-size:16px;">class ThreadDemo1  
  2. {  
  3.     public static void main(String [] args)  
  4.     {  
  5.         Thread tt =new TestThread();  
  6.         tt.start();  
  7.         int index=0;  
  8.         while(true)  
  9.         {  
  10.             if(index++==1000)  
  11.                 try {tt.join();} catch (InterruptedException e) {}  
  12.             System.out.println("main():"+Thread.currentThread().getName());  
  13.         }  
  14.     }  
  15. }  
  16. class TestThread extends Thread  
  17. {  
  18.     public void run()  
  19.     {  
  20.         while(true)  
  21.         {  
  22.             System.out.println("run():"+Thread.currentThread().getName());  
  23.         }  
  24.     }  
  25. }</span>  

以上示例代码是将两个线程同时开启,当while循环1000次以后两个线程就会合并成一个线程来执行,那我们如何再恢复两个进程分开执行呢,我们只需要将tt.join(10000);方法中传递时间值就可以了,表示合并10秒后再分开执行两个进程 。

 

四、 使用Runnable接口创建多线程

    

Runnable接口创建多线程示例:

  1. class ThreadDemo1  
  2. {  
  3.     public static void main(String [] args)  
  4.     {  
  5.         Thread tt =new Thread(new TestThread());  
  6.         tt.start();  
  7.         int index=0;  
  8.         while(true)  
  9.         {  
  10.             if(index++==100)  
  11.                 try {tt.join();} catch (InterruptedException e) {}  
  12.             System.out.println("main():"+Thread.currentThread().getName());  
  13.         }  
  14.     }  
  15. }  
  16. class TestThread implements  Runnable  
  17. {  
  18.     public void run()  
  19.     {  
  20.         while(true)  
  21.         {  
  22.             System.out.println("run():"+Thread.currentThread().getName());  
  23.         }  
  24.     }  
  25. }  

       实现runnable接口同样也可以创建多线程,它和继承Thread两者有什么区别呢,假设我们要模拟卖票,有四个窗口共同卖100张票,那我们就要同时创建出四个线程来卖100张票,那我们使用继承Thread方式来模拟的话,它会将每个线程各创建100张票,这就不符合我们的要求了,而用实现接口这种方式的话,就可以实现上述要求,所以说实现runnable接口创建多线程会更加的灵活。以下是实现runnable接口来模拟卖票:

  1. class ThreadDemo1  
  2. {  
  3.     public static void main(String [] args)  
  4.     {  
  5.         TestThread tt =new  TestThread();  
  6.         new Thread(tt).start();  
  7.         new Thread(tt).start();  
  8.         new Thread(tt).start();  
  9.         new Thread(tt).start();  
  10.     }  
  11. }  
  12. class TestThread implements  Runnable  
  13. {  
  14.     int tickets=100;  
  15.     public void run()  
  16.     {  
  17.         while(true)  
  18.         {  
  19.             if(tickets>0)  
  20.             System.out.println(Thread.currentThread().getName()+"is saling ticket"+tickets--);  
  21.         }  
  22.     }  
  23. }  


 

       Runnable接口创建多线程适合多个相同程序代码的线程去处理同一资源的情况,把虚拟CPU(线程)同程序的代码、数据有效的分离,较好的体现了面向对象的设计思想,可以避免由于java单继承特性带来的局限性。我们经常碰到这样一种情况,既当我们要将已经继承了某一个类的子类放入多线程中,由于一个类不能同时有两个父类,所以不能用继承Thread类的方式,那么,这个只能采用实现Runable

       当线程被构造时,需要代码和数据通过一个对象作为构造函数实参传递进去,这个对象就是一个实现了Runable接口的类的实例

           事实上,几乎所有多线程应用都可用Runable接口方式

五、 多线程在实际中的应用

       网络聊天程序的收发:

       1)如果一方从键盘上读取了数据并发给了对方,程序运行到“读取对方回送的数据”如果对方没有回应,就一直等待对方回送的数据,程序不能再做其他任何事情,这时程序处于阻塞状态,即使用户想正常终止程序运行都不可能,更不能实现再给对方发送一条消息,催促对方赶快应答这件事情。

         2)如果程序没有事先从键盘上读取数据并向外发送,程序将一直在"从键盘上读取数据"处阻塞,即使有数据从网上发过来,程序无法到达"读取对方回送的数据处"程序将不能收到别处 先主动发过来的数据。



          如果是多线程,我们可以将发送和接收分为两个线程来处理,如下图所示,其中线程2为接收线程,线程1为发送线程,即使用户在正在从键盘上读取数据的时候,也可以读取到对方发过来的数据,不会受到键盘输入的约束,互不影响

 

 

 

六、 多线程的同步

     1.线程安全问题

           对上述买票多线程实例会发生意外,这个意外就是,同一个票号有可能打印出多次,有可能也打印出负数零,这就不服和我们的要求了,为了能够直观的显示出来,把以上代码if语句块修改为:

  1. if(tickets>0){  
  2.     try {  
  3.         Thread.sleep(10);  
  4.     } catch (InterruptedException e) {e.printStackTrace();}  
  5.     System.out.println(Thread.currentThread().getName()+"is saling ticket"+tickets--);  
  6. }  

这样就可以看问题所在。要解决这个问题就是不能有个两个或以上的线程在if代码块中执行,这就需要使用同步语句块来执行。

     2.同步语句块解决安全问题

           将上述代码修改为:

  1. class TestThread implements  Runnable  
  2. {  
  3.     int tickets=100;  
  4.     String str=new String("");  
  5.     public void run()  
  6.     {   
  7.         while(true)  
  8.         {  
  9.             synchronized (str) {  
  10.             if(tickets>0){   
  11.                 try {  
  12.                     Thread.sleep(10);  
  13.                 } catch (InterruptedException e) {e.printStackTrace();}  
  14.                 System.out.println(Thread.currentThread().getName()+"is saling ticket"+tickets--);  
  15.             }  
  16.             }  
  17.         }  
  18.     }  
  19. }  


        加上同步代码块即可解决,synchronized 要跟一个对象。执行原理是:当后边这个对象的标志位为1时,就会有一个线程去执行这段代码,当有一个线程去执行时,那个对象的标志位就会由1变为0,再来一个线程去执行发现标志位变成0了,此时就会发生阻塞,等待标志位变为1时就会再次执行,这就保证了线程的同步。对象的标志位也叫锁旗标。线程的同步语句是以牺牲程序的性能为代价的,所以代码如果不存在线程安全的问题时,尽量不要使用同步代码块。

     3.同步函数

使用同步函数也可以解决线程不安全的问题,在方法前面使用synchronized,如:

  1. class TestThread implements  Runnable  
  2. {  
  3.     int tickets=100;  
  4.     String str=new String("");  
  5.     public void run()  
  6.     {   
  7.         while(true)  
  8.         {  
  9.             sale();  
  10.         }  
  11.     }  
  12.     public synchronized void sale(){  
  13.             if(tickets>0){   
  14.                 try {Thread.sleep(10);} catch (InterruptedException e) {e.printStackTrace();}  
  15.                 System.out.println(Thread.currentThread().getName()+"is saling ticket"+tickets--);  
  16.             }  
  17.     }  
  18. }  

 

     4.代码块与函数间同步

要想代码块要和函数同步的话,他们必须共用一个对象的标志位,那同步函数函数它用的是哪个对象呢,先来看一下以下代码:

  1. class ThreadDemo1  
  2. {  
  3.     public static void main(String [] args)  
  4.     {  
  5.         TestThread tt =new  TestThread();  
  6.         new Thread(tt).start();  
  7.         try {Thread.sleep(1);} catch (InterruptedException e) {e.printStackTrace();}  
  8.         tt.str=new String ("method");      
  9.         new Thread(tt).start();  
  10.     }  
  11. }  
  12. class TestThread implements  Runnable  
  13. {  
  14.     int tickets=100;  
  15.     String str=new String("");  
  16.     public void run()  
  17.     {   
  18.         if(str.equals("method")){  
  19.             while(true)  
  20.             {  
  21.                 sale();  
  22.             }  
  23.         }else{  
  24.             while(true)  
  25.             {   
  26.                 synchronized (str) {  
  27.                     if(tickets>0){   
  28.                         try {Thread.sleep(10);} catch (InterruptedException e) {e.printStackTrace();}  
  29.                         System.out.print("sqlle():");  
  30.                         System.out.println(Thread.currentThread().getName()+"is saling ticket"+tickets--);  
  31.                     }  
  32.                 }  
  33.             }   
  34.         }  
  35.     }  
  36.     public synchronized void sale(){  
  37.             if(tickets>0){   
  38.                 try {Thread.sleep(10);} catch (InterruptedException e) {e.printStackTrace();}  
  39.                 System.out.println(Thread.currentThread().getName()+"is saling ticket"+tickets--);  
  40.             }  
  41.     }  
  42. }  

运行的结果是不同步的,也就是说明他们共用不同的对象标志位,实验表明函数用的对象是this,如果我们将代码块改为this对象就可以实现同步,修改为:

  1. public void run()  
  2. {   
  3.     if(str.equals("method")){  
  4.         while(true)  
  5.         {  
  6.             sale();  
  7.         }  
  8.     }else{  
  9.         while(true)  
  10.         {   
  11.             synchronized (this) {  
  12.                 if(tickets>0){   
  13.                     try {Thread.sleep(10);} catch (InterruptedException e) {e.printStackTrace();}  
  14.                     System.out.print("sqlle():");  
  15.                     System.out.println(Thread.currentThread().getName()+"is saling ticket"+tickets--);  
  16.                 }  
  17.             }  
  18.         }   
  19.     }  
  20. }<span style="font-family:微软雅黑;font-size:18px;color:#666666;"></span>  

 

七、 线程间的通信

有两个缓冲分别用来存放姓名和性别,默认存放的是张三、男,生产者用来放入数据,消费者用来取数据,当生产者放入李四缓冲中的时候,性别还没有放,这时消费者的另一个线程来取数据的时候,取到的时李四、男,这显然是不合适的,这就产生了线程不同步的问题,正确的取法是,当生产者全部把姓名和性别全部存到缓冲中的时候,才能进行消费操作。

  1. //生产者不断生产数据  
  2. class Producer implements Runnable {  
  3.     Q q;  
  4.     public Producer(Q q)  
  5.     {  
  6.         this.q=q;  
  7.     }  
  8.     public void run(){  
  9.         int i=0;  
  10.         while(true)  
  11.         {  
  12.                 if(i==0)  
  13.                 {  
  14.                     q.name="zhagnsan";  
  15.                     try{Thread.sleep(1);}catch(Exception e){}  
  16.                     q.sex="male";  
  17.                 }  
  18.                 else  
  19.                 {  
  20.                     q.name="lisi";  
  21.                     q.sex="female";  
  22.                 }  
  23.             i=(i+1)%2;  
  24.         }  
  25.     }  
  26. }  
  27. //消费者取数据  
  28. class Consumer implements Runnable{  
  29.     Q q;  
  30.     public Consumer(Q q)  
  31.     {  
  32.         this.q=q;  
  33.     }  
  34.     public void run()  
  35.     {  
  36.         while(true)  
  37.         {  
  38.                 System.out.print(q.name);  
  39.                 System.out.println(":"+q.sex);  
  40.         }  
  41.     }  
  42. }  
  43. class Q   
  44. {  
  45.     String name="";  
  46.     String sex="";  
  47. }  
  48. class ThreadCommunation  
  49. {  
  50.     public static void main(String [] args)  
  51.     {  
  52.         Q q =new Q();  
  53.         new Thread(new Producer(q)).start();  
  54.         new Thread(new Consumer(q)).start();  
  55.     }  
  56. }  


这段代码就会带来线程问题,取出的数据是zhangsan,female,这里只需要使用同一个对象的同步代码快,虽然两个代码块不在同一个类中,但使用的同一个对象,这样也可实现同步

解决如下:

  1. class Producer implements Runnable {  
  2.     Q q;  
  3.     public Producer(Q q)  
  4.     {  
  5.         this.q=q;  
  6.     }  
  7.     public void run(){  
  8.         int i=0;  
  9.         while(true)  
  10.         {  
  11.             synchronized (q) {  
  12.                 if(i==0)  
  13.                 {  
  14.                     q.name="zhagnsan";  
  15.                     try{Thread.sleep(1);}catch(Exception e){}  
  16.                     q.sex="male";  
  17.                 }  
  18.                 else  
  19.                 {  
  20.                     q.name="lisi";  
  21.                     q.sex="female";  
  22.                 }  
  23.                 i=(i+1)%2;  
  24.             }  
  25.         }  
  26.     }  
  27. }  
  28.   
  29. class Consumer implements Runnable{  
  30.     Q q;  
  31.     public Consumer(Q q)  
  32.     {  
  33.         this.q=q;  
  34.     }  
  35.     public void run()  
  36.     {  
  37.         while(true)  
  38.         {  
  39.             synchronized (q) {  
  40.                 System.out.print(q.name);  
  41.                 System.out.println(":"+q.sex);  
  42.             }  
  43.         }  
  44.     }  
  45. }  
  46. class Q  
  47. {  
  48.     String name="";  
  49.     String sex="";  
  50. }  
  51. class ThreadCommunation  
  52. {  
  53.     public static void main(String [] args)  
  54.     {  
  55.         Q q =new Q();  
  56.         new Thread(new Producer(q)).start();  
  57.         new Thread(new Consumer(q)).start();  
  58.     }  
  59. }  

运行后,虽然读和取同步了,但是还会出现取的时候,有可能会取多个,我们如何避免这个问题呢,这就使用到了线程间的通信,关于线程通信有四个方法:

wait:告诉当前线程放弃监视器并进入睡眠状态直到其他线程进入同一监视器并调用notify为止。

notify:唤醒同一个对象监视器中调用wait的第一个线程。

notifyAll:唤醒同一个对象监视器中调用wait的所有线程,具有最高优先级的线程首先被唤醒并执行。
解决方案如下:

  1. class Producer implements Runnable {  
  2.     Q q;  
  3.     public Producer(Q q)  
  4.     {  
  5.         this.q=q;  
  6.     }  
  7.     public void run(){  
  8.         int i=0;  
  9.         while(true)  
  10.         {  
  11.             synchronized (q) {  
  12.                 if(q.bFull)  
  13.                     try {q.wait();} catch (InterruptedException e) {e.printStackTrace();}  
  14.                 if(i==0)  
  15.                 {  
  16.                     q.name="zhagnsan";  
  17.                     try{Thread.sleep(1);}catch(Exception e){}  
  18.                     q.sex="male";  
  19.                 }  
  20.                 else  
  21.                 {  
  22.                     q.name="lisi";  
  23.                     q.sex="female";  
  24.                 }  
  25.                 q.bFull=true;  
  26.                 q.notify();  
  27.             }  
  28.              i=(i+1)%2;  
  29.         }  
  30.     }  
  31. }  
  32.   
  33. class Consumer implements Runnable{  
  34.     Q q;  
  35.     public Consumer(Q q)  
  36.     {  
  37.         this.q=q;  
  38.     }  
  39.     public void run()  
  40.     {  
  41.         while(true)  
  42.         {  
  43.             synchronized (q) {  
  44.                 if(!q.bFull)  
  45.                 try {q.wait();} catch (InterruptedException e) {e.printStackTrace();}  
  46.                 System.out.print(q.name);  
  47.                 System.out.println(":"+q.sex);  
  48.                 q.bFull=false;  
  49.                 q.notify();  
  50.             }  
  51.         }  
  52.     }  
  53. }  
  54. class Q  
  55. {  
  56.     String name="";  
  57.     String sex="";  
  58.     boolean bFull=false;  
  59. }  
  60. class ThreadCommunation  
  61. {  
  62.     public static void main(String [] args)  
  63.     {  
  64.         Q q =new Q();  
  65.         new Thread(new Producer(q)).start();  
  66.         new Thread(new Consumer(q)).start();  
  67.     }  
  68. }  

这样就可以实现生产一个取一个,不会出现消费者还没有取的情况下生产者就放入新的数据,也不会出现生产者还没有生产新的数据的时候消费者就取原来的数据。

原文地址http://blog.csdn.net/furongkang/article/details/6769965
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值