在路上

 找回密码
 立即注册
在路上 站点首页 学习 查看内容

最全面的Java多线程用法解析

2016-12-13 12:56| 发布者: zhangjf| 查看: 595| 评论: 0

摘要: 最全面的java多线程用法解析,如果你对Java的多线程机制并没有深入的研究,那么本文可以帮助你更透彻地理解Java多线程的原理以及使用方法。 1.创建线程 在Java中创建线程有两种方法:使用Thread类和使用Runnable ...

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

1.创建线程

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

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);

方法一:继承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. class Demo extends Thread{
  11. public void run(){
  12. for(int i=0;i<60;i++){
  13. System.out.println(Thread.currentThread().getName()+i);
  14. }
  15. }
  16. }
复制代码

方法二:

  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方法的定义如下:

publicstaticvoid sleep(long millis) throws InterruptedException publicstaticvoid 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 block
  23. 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. public void run(){
  21. while(true){
  22. saleTicket();
  23. }
  24. }
  25. }
复制代码

同步函数锁是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....nv
  41. lili....男
  42. 张三....nv
  43. lili....男
  44. */
复制代码

修改上面代码

  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. }).start();
  30. new Thread(new Runnable(){
  31. public void run(){
  32. while(true){
  33. synchronized (p) {
  34. p.get();
  35. }
  36. }
  37. }
  38. }).start();
  39. }
  40. }
  41. /*
  42. lili....nv
  43. lili....nv
  44. lili....nv
  45. lili....nv
  46. lili....nv
  47. lili....nv
  48. 张三....男
  49. 张三....男
  50. 张三....男
  51. 张三....男
  52. */
复制代码

等待唤醒机制

  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 block
  30. 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 block
  53. 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 block
  13. 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 block
  26. e.printStackTrace();
  27. }
  28. System.out.println("消费了******"+name);
  29. flags =false;
  30. notifyAll();
  31. }
  32. }
  33. final Goods g =new Goods();
  34. new Thread(new Runnable(){
  35. public void run(){
  36. while(true){
  37. g.produce("商品");
  38. }
  39. }
  40. }).start();
  41. new Thread(new Runnable(){
  42. public void run(){
  43. while(true){
  44. g.consume();
  45. }
  46. }
  47. }).start();
  48. }
  49. }
复制代码

生产消费机制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 block
  13. 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 block
  26. e.printStackTrace();
  27. }
  28. System.out.println(Thread.currentThread().getName()+"消费了******"+name);
  29. flags =false;
  30. notifyAll();
  31. }
  32. }
  33. final Goods g =new Goods();
  34. new Thread(new Runnable(){
  35. public void run(){
  36. while(true){
  37. g.produce("商品");
  38. }
  39. }
  40. },"生产者一号").start();
  41. new Thread(new Runnable(){
  42. public void run(){
  43. while(true){
  44. g.produce("商品");
  45. }
  46. }
  47. },"生产者二号").start();
  48. new Thread(new Runnable(){
  49. public void run(){
  50. while(true){
  51. g.consume();
  52. }
  53. }
  54. },"消费者一号").start();
  55. new Thread(new Runnable(){
  56. public void run(){
  57. while(true){
  58. g.consume();
  59. }
  60. }
  61. },"消费者二号").start();
  62. }
  63. }
  64. /*
  65. 消费者二号消费了******商品编号:48049
  66. 生产者一号生产了....商品编号:48050
  67. 消费者一号消费了******商品编号:48050
  68. 生产者一号生产了....商品编号:48051
  69. 消费者二号消费了******商品编号:48051
  70. 生产者二号生产了....商品编号:48052
  71. 消费者二号消费了******商品编号:48052
  72. 生产者一号生产了....商品编号:48053
  73. 消费者一号消费了******商品编号:48053
  74. 生产者一号生产了....商品编号:48054
  75. 消费者二号消费了******商品编号:48054
  76. 生产者二号生产了....商品编号:48055
  77. 消费者二号消费了******商品编号:48055
  78. */
复制代码
来源:codeceo

最新评论

小黑屋|在路上 ( 蜀ICP备15035742号-1 

;

GMT+8, 2025-7-7 11:41

Copyright 2015-2025 djqfx

返回顶部