博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
最全面的Java多线程用法解析
阅读量:7040 次
发布时间:2019-06-28

本文共 14477 字,大约阅读时间需要 48 分钟。

最全面的java多线程用法解析,如果你对Java的多线程机制并没有深入的研究,那么本文可以帮助你更透彻地理解Java多线程的原理以及使用方法。

 

1.创建线程

  • public Thread( );

  • public Thread(Runnable target);

  • public Thread(String name);

  • public Thread(Runnable target, String name);

  • public Thread(ThreadGroup group, Runnable target);

  • public Thread(ThreadGroup group, String name);

  • public Thread(ThreadGroup group, Runnable target, String name);

  • public Thread(ThreadGroup group, Runnable target, String name, long stackSize);

 

在Java中创建线程有两种方法:使用Thread类和使用Runnable接口。在使用Runnable接口时需要建立一个Thread实例。因此,无论是通过Thread类还是Runnable接口建立线程,都必须建立Thread类或它的子类的实例。Thread构造函数:

方法一:继承Thread类覆盖run方法

  

1 public class ThreadDemo1 { 2      public static void main(String[] args){ 3          Demo d = new Demo(); 4          d.start(); 5          for(int i=0;i<60;i++){ 6              System.out.println(Thread.currentThread().getName()+i); 7          } 8  9      }10  }11  class Demo extends Thread{12      public void run(){13          for(int i=0;i<60;i++){14              System.out.println(Thread.currentThread().getName()+i);15          }16      } }

 

方法二:使用Runnable接口。在使用Runnable接口时需要建立一个Thread实例。

1 public class ThreadDemo2 { 2     public static void main(String[] args){ 3         Demo2 d =new Demo2(); 4         Thread t = new Thread(d); 5         t.start(); 6         for(int x=0;x<60;x++){ 7             System.out.println(Thread.currentThread().getName()+x); 8         } 9     }10 }11 class Demo2 implements Runnable{12     public void run(){13         for(int x=0;x<60;x++){14             System.out.println(Thread.currentThread().getName()+x);15         }16     }17 }

2.线程的生命周期

  与人有生老病死一样,线程也同样要经历开始(等待)、运行、挂起和停止四种不同的状态。这四种状态都可以通过Thread类中的方法进行控制。下面给出了Thread类中和这四种状态相关的方法。  

 // 开始线程

  • publicvoid start( );

  • publicvoid run( );

    // 挂起和唤醒线程

  • publicvoid resume( );     // 不建议使用

  • publicvoid suspend( );    // 不建议使用

  • publicstaticvoid sleep(long millis);

  • publicstaticvoid sleep(long millis, int nanos);

    // 终止线程

  • publicvoid stop( );       // 不建议使用

  • publicvoid interrupt( );

    // 得到线程状态

  • publicboolean isAlive( );

  • publicboolean isInterrupted( );

  • publicstaticboolean interrupted( );

    // join方法

  • publicvoid join( ) throws InterruptedException;

 

  

线程在建立后并不马上执行run方法中的代码,而是处于等待状态。线程处于等待状态时,可以通过Thread类的方法来设置线程不各种属性,如线程的优先级(setPriority)、线程名(setName)和线程的类型(setDaemon)等。

当调用start方法后,线程开始执行run方法中的代码。线程进入运行状态。可以通过Thread类的isAlive方法来判断线程是否处于运行状态。当线程处于运行状态时,isAlive返回true,当isAlive返回false时,可能线程处于等待状态,也可能处于停止状态。下面的代码演示了线程的创建、运行和停止三个状态之间的切换,并输出了相应的isAlive返回值。

一但线程开始执行run方法,就会一直到这个run方法执行完成这个线程才退出。但在线程执行的过程中,可以通过两个方法使线程暂时停止执行。这两个方法是suspend和sleep。在使用suspend挂起线程后,可以通过resume方法唤醒线程。而使用sleep使线程休眠后,只能在设定的时间后使线程处于就绪状态(在线程休眠结束后,线程不一定会马上执行,只是进入了就绪状态,等待着系统进行调度)。

在使用sleep方法时有两点需要注意:

1. sleep方法有两个重载形式,其中一个重载形式不仅可以设毫秒,而且还可以设纳秒(1,000,000纳秒等于1毫秒)。但大多数操作系统平台上的Java虚拟机都无法精确到纳秒,因此,如果对sleep设置了纳秒,Java虚拟机将取最接近这个值的毫秒。

2. 在使用sleep方法时必须使用throws或try{…}catch{…}。因为run方法无法使用throws,所以只能使用try{…}catch{…}。当在线程休眠的过程中,使用interrupt方法中断线程时sleep会抛出一个InterruptedException异常。sleep方法的定义如下:

  • public static void sleep(long millis) throws InterruptedException

  • public static void sleep(long millis, int nanos) throws InterruptedException

     

有三种方法可以使终止线程。

1.  使用退出标志,使线程正常退出,也就是当run方法完成后线程终止。

2.  使用stop方法强行终止线程(这个方法不推荐使用,因为stop和suspend、resume一样,也可能发生不可预料的结果)。

3.  使用interrupt方法中断线程。

1. 使用退出标志终止线程

当run方法执行完后,线程就会退出。但有时run方法是永远不会结束的。如在服务端程序中使用线程进行监听客户端请求,或是其他的需要循环处理的任务。在这种情况下,一般是将这些任务放在一个循环中,如while循环。如果想让循环永远运行下去,可以使用while(true){…}来处理。但要想使while循环在某一特定条件下退出,最直接的方法就是设一个boolean类型的标志,并通过设置这个标志为true或false来控制while循环是否退出。下面给出了一个利用退出标志终止线程的例子。

join方法的功能就是使异步执行的线程变成同步执行。也就是说,当调用线程实例的start方法后,这个方法会立即返回,如果在调用start方法后后需要使用一个由这个线程计算得到的值,就必须使用join方法。如果不使用join方法,就不能保证当执行到start方法后面的某条语句时,这个线程一定会执行完。而使用join方法后,直到这个线程退出,程序才会往下执行。下面的代码演示了join的用法。

 

 

3.多线程安全问题 

问题原因:当多条语句在操作同一个线程共享数据时,一个线程对多条语句只执行了一部分,还没执行完,另一个线程参与进来执行,导致共享数据的错误。

解决办法:对多条操作共享数据的语句,只能让一个线程都执行完,在执行过程中,其他线程不执行。

同步代码块:

1 public class ThreadDemo3 { 2     public static void main(String[] args){ 3         Ticket t =new Ticket(); 4         Thread t1 = new Thread(t,"窗口一"); 5         Thread t2 = new Thread(t,"窗口二"); 6         Thread t3 = new Thread(t,"窗口三"); 7         Thread t4 = new Thread(t,"窗口四"); 8         t1.start(); 9         t2.start();10         t3.start();11         t4.start();12     }13 }14 class Ticket implements Runnable{15     private int ticket =400;16     public void run(){17         while(true){18             synchronized (new Object()) {19                 try {20                     Thread.sleep(1);21                 } catch (InterruptedException e) {22                     // TODO Auto-generated catch block23                     e.printStackTrace();24                 }25                 if(ticket<=0)26                     break;27                 System.out.println(Thread.currentThread().getName()+"---卖出"+ticket--);28             }29         }30     }31 }

同步函数

1 public class ThreadDemo3 { 2     public static void main(String[] args){ 3         Ticket t =new Ticket(); 4         Thread t1 = new Thread(t,"窗口一"); 5         Thread t2 = new Thread(t,"窗口二"); 6         Thread t3 = new Thread(t,"窗口三"); 7         Thread t4 = new Thread(t,"窗口四"); 8         t1.start(); 9         t2.start();10         t3.start();11         t4.start();12     }13 }14 class Ticket implements Runnable{15     private int ticket = 4000;16     public synchronized void  saleTicket(){17         if(ticket>0)18             System.out.println(Thread.currentThread().getName()+"卖出了"+ticket--);19 20     }21     public void run(){22         while(true){23             saleTicket();24         }25     }26 }

 

同步函数锁是this 静态同步函数锁是class

线程间的通信

 

1 public class ThreadDemo3 { 2     public static void main(String[] args){ 3         class Person{ 4             public String name; 5             private String gender; 6             public void set(String name,String gender){ 7                 this.name =name; 8                 this.gender =gender; 9             }10             public void get(){11                 System.out.println(this.name+"...."+this.gender);12             }13         }14         final Person p =new Person();15         new Thread(new Runnable(){16             public void run(){17                 int x=0;18                 while(true){19                     if(x==0){20                         p.set("张三", "男");21                     }else{22                         p.set("lili", "nv");23                     }24                     x=(x+1)%2;25                 }26             }27         }).start();28         new Thread(new Runnable(){29             public void run(){30                 while(true){31                     p.get();32                 }33             }34         }).start();35     }36 }37 /*38 张三....男39 张三....男40 lili....nv41 lili....男42 张三....nv43 lili....男

修改上面代码

1 public class ThreadDemo3 { 2      public static void main(String[] args){ 3          class Person{ 4              public String name; 5              private String gender; 6              public void set(String name,String gender){ 7                  this.name =name; 8                  this.gender =gender; 9              }10              public void get(){11                  System.out.println(this.name+"...."+this.gender);12              }13          }14          final Person p =new Person();15          new Thread(new Runnable(){16              public void run(){17                  int x=0;18                  while(true){19                      synchronized (p) {20                          if(x==0){21                              p.set("张三", "男");22                          }else{23                              p.set("lili", "nv");24                          }25                          x=(x+1)%2;    26                      }27 28                  }29              }30          }).start();31          new Thread(new Runnable(){32              public void run(){33                  while(true){34                      synchronized (p) {35                          p.get();36                      }37                  }38              }39          }).start();40      }41 42  }43  /*44  lili....nv45  lili....nv46  lili....nv47  lili....nv48  lili....nv49  lili....nv50  张三....男51  张三....男52  张三....男53  张三....男54  */

等待唤醒机制

1 /* 2  *线程等待唤醒机制 3  *等待和唤醒必须是同一把锁  4  */ 5 public class ThreadDemo3 { 6     private static boolean flags =false; 7     public static void main(String[] args){ 8         class Person{ 9             public String name;10             private String gender;11             public void set(String name,String gender){12                 this.name =name;13                 this.gender =gender;14             }15             public void get(){16                 System.out.println(this.name+"...."+this.gender);17             }18         }19         final Person p =new Person();20         new Thread(new Runnable(){21             public void run(){22                 int x=0;23                 while(true){24                     synchronized (p) {25                         if(flags)26                             try {27                                 p.wait();28                             } catch (InterruptedException e) {29                                 // TODO Auto-generated catch block30                                 e.printStackTrace();31                             };32                         if(x==0){33                             p.set("张三", "男");34                         }else{35                             p.set("lili", "nv");36                         }37                         x=(x+1)%2;38                         flags =true;39                         p.notifyAll();40                     }41                 }42             }43         }).start();44         new Thread(new Runnable(){45             public void run(){46                 while(true){47                     synchronized (p) {48                         if(!flags)49                             try {50                                 p.wait();51                             } catch (InterruptedException e) {52                                 // TODO Auto-generated catch block53                                 e.printStackTrace();54                             };55                         p.get();56                         flags =false;57                         p.notifyAll();58                         }59                 }60             }61         }).start();62     }63 }

生产消费机制一

1 public class ThreadDemo4 { 2     private static boolean flags =false; 3     public static void main(String[] args){ 4         class Goods{ 5             private String name; 6             private int num; 7             public synchronized void produce(String name){ 8                 if(flags) 9                     try {10                         wait();11                     } catch (InterruptedException e) {12                         // TODO Auto-generated catch block13                         e.printStackTrace();14                     }15                 this.name =name+"编号:"+num++;16                 System.out.println("生产了...."+this.name);17                 flags =true;18                 notifyAll();19             }20             public synchronized void consume(){21                 if(!flags)22                     try {23                         wait();24                     } catch (InterruptedException e) {25                         // TODO Auto-generated catch block26                         e.printStackTrace();27                     }28                 System.out.println("消费了******"+name);29                 flags =false;30                 notifyAll();31             }32 33         }34         final Goods g =new Goods();35         new Thread(new Runnable(){36             public void run(){37                 while(true){38                     g.produce("商品");39                 }40             }41         }).start();42         new Thread(new Runnable(){43             public void run(){44                 while(true){45                     g.consume();46                 }47             }48         }).start();49     }50 }

生产消费机制2

1 public class ThreadDemo4 { 2     private static boolean flags =false; 3     public static void main(String[] args){ 4         class Goods{ 5             private String name; 6             private int num; 7             public synchronized void produce(String name){ 8                 while(flags) 9                     try {10                         wait();11                     } catch (InterruptedException e) {12                         // TODO Auto-generated catch block13                         e.printStackTrace();14                     }15                 this.name =name+"编号:"+num++;16                 System.out.println(Thread.currentThread().getName()+"生产了...."+this.name);17                 flags =true;18                 notifyAll();19             }20             public synchronized void consume(){21                 while(!flags)22                     try {23                         wait();24                     } catch (InterruptedException e) {25                         // TODO Auto-generated catch block26                         e.printStackTrace();27                     }28                 System.out.println(Thread.currentThread().getName()+"消费了******"+name);29                 flags =false;30                 notifyAll();31             }32 33         }34         final Goods g =new Goods();35         new Thread(new Runnable(){36             public void run(){37                 while(true){38                     g.produce("商品");39                 }40             }41         },"生产者一号").start();42         new Thread(new Runnable(){43             public void run(){44                 while(true){45                     g.produce("商品");46                 }47             }48         },"生产者二号").start();49         new Thread(new Runnable(){50             public void run(){51                 while(true){52                     g.consume();53                 }54             }55         },"消费者一号").start();56         new Thread(new Runnable(){57             public void run(){58                 while(true){59                     g.consume();60                 }61             }62         },"消费者二号").start();63     }64 }65 /*66 消费者二号消费了******商品编号:4804967 生产者一号生产了....商品编号:4805068 消费者一号消费了******商品编号:4805069 生产者一号生产了....商品编号:4805170 消费者二号消费了******商品编号:4805171 生产者二号生产了....商品编号:4805272 消费者二号消费了******商品编号:4805273 生产者一号生产了....商品编号:4805374 消费者一号消费了******商品编号:4805375 生产者一号生产了....商品编号:4805476 消费者二号消费了******商品编号:4805477 生产者二号生产了....商品编号:4805578 消费者二号消费了******商品编号:48055

 

转载于:https://www.cnblogs.com/XQiu/p/5174782.html

你可能感兴趣的文章
在 Windows 7 和 Windows Server 2008 R2 上安装 Windows PowerShell 3.0
查看>>
专访IBM Power总经理 纵览Power 7新特性
查看>>
如何选购台式电脑和笔记本?购买时应注意什么
查看>>
Spring MVC基于注解来格式化数据
查看>>
mysql主从同步错误解决和Slave_IO_Running: NO
查看>>
编码问题之:java.io.UTFDataFormatException: Invalid byte 2 of 2-byte UTF-8 sequence.
查看>>
配置samba服务
查看>>
查找对话框实现
查看>>
Microsoft活动目录的作用以及优势
查看>>
小五思科技术学习笔记之单区域OSPF
查看>>
Hyper-V Server存储介绍
查看>>
[图示]神相的‘敏捷项目管理’
查看>>
更换云服务器上的Python版本
查看>>
Skype for Business Server 2015-04-前端服务器-7-部署
查看>>
你的Postfix邮件服务器安全么?
查看>>
站在巨人肩膀看清IT馅饼和陷阱
查看>>
Android系统匿名共享内存(Anonymous Shared Memory)C++调用接口分析(4)
查看>>
Windows 7 的一些使用技巧
查看>>
Spring Boot中使用Redis数据库
查看>>
完整性检查工具Nabou
查看>>