当前位置: 移动技术网 > IT编程>开发语言>Java > java 基础教程之多线程详解及简单实例

java 基础教程之多线程详解及简单实例

2019年07月22日  | 移动技术网IT编程  | 我要评论
java 多线程详解 在这篇文章里,我们关注多线程。多线程是一个复杂的话题,包含了很多内容,这篇文章主要关注线程的基本属性、如何创建线程、线程的状态切换以及线程通信。

java 多线程详解

在这篇文章里,我们关注多线程。多线程是一个复杂的话题,包含了很多内容,这篇文章主要关注线程的基本属性、如何创建线程、线程的状态切换以及线程通信。

  线程是操作系统运行的基本单位,它被封装在进程中,一个进程可以包含多个线程。即使我们不手动创造线程,进程也会有一个默认的线程在运行。

  对于jvm来说,当我们编写一个单线程的程序去运行时,jvm中也是有至少两个线程在运行,一个是我们创建的程序,一个是垃圾回收。

  线程基本信息

  我们可以通过thread.currentthread()方法获取当前线程的一些信息,并对其进行修改。

  我们来看以下代码:

查看并修改当前线程的属性
string name = thread.currentthread().getname();
    int priority = thread.currentthread().getpriority();
    string groupname = thread.currentthread().getthreadgroup().getname();
    boolean isdaemon = thread.currentthread().isdaemon();
    system.out.println("thread name:" + name);
    system.out.println("priority:" + priority);
    system.out.println("group name:" + groupname);
    system.out.println("isdaemon:" + isdaemon);
    
    thread.currentthread().setname("test");
    thread.currentthread().setpriority(thread.max_priority);
    name = thread.currentthread().getname();
    priority = thread.currentthread().getpriority();
    groupname = thread.currentthread().getthreadgroup().getname();
    isdaemon = thread.currentthread().isdaemon();
    system.out.println("thread name:" + name);
    system.out.println("priority:" + priority);

  其中列出的属性说明如下:

  1. groupname,每个线程都会默认在一个线程组里,我们也可以显式的创建线程组,一个线程组中也可以包含子线程组,这样线程和线程组,就构成了一个树状结构。
  2. name,每个线程都会有一个名字,如果不显式指定,那么名字的规则是“thread-xxx”。
  3. priority,每个线程都会有自己的优先级,jvm对优先级的处理方式是“抢占式”的。当jvm发现优先级高的线程时,马上运行该线程;对于多个优先级相等的线程,jvm对其进行轮询处理。java的线程优先级从1到10,默认是5,thread类定义了2个常量:min_priority和max_priority来表示最高和最低优先级。

我们可以看下面的代码,它定义了两个不同优先级的线程:

线程优先级示例
public static void prioritytest()
{
  thread thread1 = new thread("low")
  {
    public void run()
    {
      for (int i = 0; i < 5; i++)
      {
        system.out.println("thread 1 is running.");
      }
    }
  };
  
  thread thread2 = new thread("high")
  {
    public void run()
    {
      for (int i = 0; i < 5; i++)
      {
        system.out.println("thread 2 is running.");
      }
    }
  };
  
  thread1.setpriority(thread.min_priority);
  thread2.setpriority(thread.max_priority);
  thread1.start();
  thread2.start();
}

从运行结果可以看出,是高优先级线程运行完成后,低优先级线程才运行。

isdaemon,这个属性用来控制父子线程的关系,如果设置为true,当父线程结束后,其下所有子线程也结束,反之,子线程的生命周期不受父线程影响。

我们来看下面的例子:

isdaemon 示例
public static void daemontest()
{
  thread thread1 = new thread("daemon")
  {
    public void run()
    {
      thread subthread = new thread("sub")
      {
        public void run()
        {
          for(int i = 0; i < 100; i++)
          {
            system.out.println("sub thread running " + i);
          }
        }
      };
      subthread.setdaemon(true);
      subthread.start();
      system.out.println("main thread end.");
    }
  };
  
  thread1.start();
}

上面代码的运行结果,在和删除subthread.setdaemon(true);后对比,可以发现后者运行过程中子线程会完成执行后再结束,而前者中,子线程很快就结束了。

  如何创建线程

  上面的内容,都是演示默认线程中的一些信息,那么应该如何创建线程呢?在java中,我们有3种方式可以用来创建线程。

  java中的线程要么继承thread类,要么实现runnable接口,我们一一道来。

  使用内部类来创建线程

  我们可以使用内部类的方式来创建线程,过程是声明一个thread类型的变量,并重写run方法。示例代码如下:

使用内部类创建线程
public static void createthreadbynestclass()
{
  thread thread = new thread()
  {
    public void run()
    {
      for (int i =0; i < 5; i++)
      {
        system.out.println("thread " + thread.currentthread().getname() + " is running.");
      }
      system.out.println("thread " + thread.currentthread().getname() + " is finished.");
    }
  };
  thread.start();
}

  继承thread以创建线程

  我们可以从thread中派生一个类,重写其run方法,这种方式和上面相似。示例代码如下:

派生thread类以创建线程
class mythread extends thread
{
  public void run()
  {
    for (int i =0; i < 5; i++)
    {
      system.out.println("thread " + thread.currentthread().getname() + " is running.");
    }
    system.out.println("thread " + thread.currentthread().getname() + " is finished.");
  }
}


public static void createthreadbysubclass()
{
  mythread thread = new mythread();
  thread.start();
}

  实现runnable接口以创建线程

  我们可以定义一个类,使其实现runnable接口,然后将该类的实例作为构建thread变量构造函数的参数。示例代码如下:

实现runnable接口以创建线程
class myrunnable implements runnable
{
  public void run() 
  {
    for (int i =0; i < 5; i++)
    {
      system.out.println("thread " + thread.currentthread().getname() + " is running.");
    }
    system.out.println("thread " + thread.currentthread().getname() + " is finished.");
  }
}


public static void createthreadbyrunnable()
{
  myrunnable runnable = new myrunnable();
  thread thread = new thread(runnable);
  thread.start();
}

  上述3种方式都可以创建线程,而且从示例代码上看,线程执行的功能是一样的,那么这三种创建方式有什么不同呢?

  这涉及到java中多线程的运行模式,对于java来说,多线程在运行时,有“多对象多线程”和“单对象多线程”的区别:

  1. 多对象多线程,程序在运行过程中创建多个线程对象,每个对象上运行一个线程。
  2. 单对象多线程,程序在运行过程中创建一个线程对象,在其上运行多个线程。

  显然,从线程同步和调度的角度来看,多对象多线程要简单一些。上述3种线程创建方式,前两种都属于“多对象多线程”,第三种既可以使用“多对象多线程”,也可以使用“单对象单线程”。

  我们来看下面的示例代码,里面会用到object.notify方法,这个方法会唤醒对象上的一个线程;而object.notifyall方法,则会唤醒对象上的所有线程。

notify示例
public class notifysample {
  
  public static void main(string[] args) throws interruptedexception
  {
    notifytest();
    notifytest2();
    notifytest3();
  }
  
  private static void notifytest() throws interruptedexception
  {
    mythread[] arrthreads = new mythread[3];
    for (int i = 0; i < arrthreads.length; i++)
    {
      arrthreads[i] = new mythread();
      arrthreads[i].id = i;
      arrthreads[i].setdaemon(true);
      arrthreads[i].start();
    }
    thread.sleep(500);
    for (int i = 0; i < arrthreads.length; i++)
    {
      synchronized(arrthreads[i])
      {
        arrthreads[i].notify();
      }
    }
  }
  
  private static void notifytest2() throws interruptedexception
  {
    myrunner[] arrmyrunners = new myrunner[3];
    thread[] arrthreads = new thread[3];
    for (int i = 0; i < arrthreads.length; i++)
    {
      arrmyrunners[i] = new myrunner();
      arrmyrunners[i].id = i;
      arrthreads[i] = new thread(arrmyrunners[i]);
      arrthreads[i].setdaemon(true);
      arrthreads[i].start();
    }
    thread.sleep(500);
    for (int i = 0; i < arrmyrunners.length; i++)
    {
      synchronized(arrmyrunners[i])
      {
        arrmyrunners[i].notify();
      }
    }
  }
  
  private static void notifytest3() throws interruptedexception
  {
    myrunner runner = new myrunner();
    thread[] arrthreads = new thread[3];
    for (int i = 0; i < arrthreads.length; i++)
    {
      arrthreads[i] = new thread(runner);
      arrthreads[i].setdaemon(true);
      arrthreads[i].start();
    }
    thread.sleep(500);

    synchronized(runner)
    {
      runner.notifyall();
    }
  }
}

class mythread extends thread
{
  public int id = 0;
  public void run()
  {
    system.out.println("第" + id + "个线程准备休眠5分钟。");
    try
    {
      synchronized(this)
      {
        this.wait(5*60*1000);
      }
    }
    catch(interruptedexception ex)
    {
      ex.printstacktrace();
    }
    system.out.println("第" + id + "个线程被唤醒。");
  }
}

class myrunner implements runnable
{
  public int id = 0;
  public void run() 
  {
    system.out.println("第" + id + "个线程准备休眠5分钟。");
    try
    {
      synchronized(this)
      {
        this.wait(5*60*1000);
      }
    }
    catch(interruptedexception ex)
    {
      ex.printstacktrace();
    }
    system.out.println("第" + id + "个线程被唤醒。");
  }
  
}

  示例代码中,notifytest()和notifytest2()是“多对象多线程”,尽管notifytest2()中的线程实现了runnable接口,但是它里面定义thread数组时,每个元素都使用了一个新的runnable实例。notifytest3()属于“单对象多线程”,因为我们只定义了一个runnable实例,所有的线程都会使用这个实例。

  notifyall方法适用于“单对象多线程”的情景,因为notify方法只会随机唤醒对象上的一个线程。

  线程的状态切换

  对于线程来讲,从我们创建它一直到线程运行结束,在这个过程中,线程的状态可能是这样的:

  1. 创建:已经有thread实例了, 但是cpu还有为其分配资源和时间片。
  2. 就绪:线程已经获得了运行所需的所有资源,只等cpu进行时间调度。
  3. 运行:线程位于当前cpu时间片中,正在执行相关逻辑。
  4. 休眠:一般是调用thread.sleep后的状态,这时线程依然持有运行所需的各种资源,但是不会被cpu调度。
  5. 挂起:一般是调用thread.suspend后的状态,和休眠类似,cpu不会调度该线程,不同的是,这种状态下,线程会释放所有资源。
  6. 死亡:线程运行结束或者调用了thread.stop方法。

  下面我们来演示如何进行线程状态切换,首先我们会用到下面方法:

  1. thread()或者thread(runnable):构造线程。
  2. thread.start:启动线程。
  3. thread.sleep:将线程切换至休眠状态。
  4. thread.interrupt:中断线程的执行。
  5. thread.join:等待某线程结束。
  6. thread.yield:剥夺线程在cpu上的执行时间片,等待下一次调度。
  7. object.wait:将object上所有线程锁定,直到notify方法才继续运行。
  8. object.notify:随机唤醒object上的1个线程。
  9. object.notifyall:唤醒object上的所有线程。

  下面,就是演示时间啦!!!

  线程等待与唤醒

  这里主要使用object.wait和object.notify方法,请参见上面的notify实例。需要注意的是,wait和notify都必须针对同一个对象,当我们使用实现runnable接口的方式来创建线程时,应该是在runnable对象而非thread对象上使用这两个方法。

  线程的休眠与唤醒

thread.sleep实例
public class sleepsample {
  
  public static void main(string[] args) throws interruptedexception
  {
    sleeptest();
  }
  
  private static void sleeptest() throws interruptedexception
  {
    thread thread = new thread()
    {
      public void run()
      {
        system.out.println("线程 " + thread.currentthread().getname() + "将要休眠5分钟。");
        try
        {
          thread.sleep(5*60*1000);
        }
        catch(interruptedexception ex)
        {
          system.out.println("线程 " + thread.currentthread().getname() + "休眠被中断。");
        }
        system.out.println("线程 " + thread.currentthread().getname() + "休眠结束。");
      }
    };
    thread.setdaemon(true);
    thread.start();
    thread.sleep(500);
    thread.interrupt();
  }

}

  线程在休眠过程中,我们可以使用thread.interrupt将其唤醒,这时线程会抛出interruptedexception。

  线程的终止

  虽然有thread.stop方法,但该方法是不被推荐使用的,我们可以利用上面休眠与唤醒的机制,让线程在处理iterruptedexception时,结束线程。

thread.interrupt示例
public class stopthreadsample {

  public static void main(string[] args) throws interruptedexception
  {
    stoptest();
  }
  
  private static void stoptest() throws interruptedexception
  {
    thread thread = new thread()
    {
      public void run()
      {
        system.out.println("线程运行中。");
        try
        {
          thread.sleep(1*60*1000);
        }
        catch(interruptedexception ex)
        {
          system.out.println("线程中断,结束线程");
          return;
        }
        system.out.println("线程正常结束。");
      }
    };
    thread.start();
    thread.sleep(500);
    thread.interrupt();
  }
}

  线程的同步等待

  当我们在主线程中创建了10个子线程,然后我们期望10个子线程全部结束后,主线程在执行接下来的逻辑,这时,就该thread.join登场了。

thread.join示例
public class joinsample {

  public static void main(string[] args) throws interruptedexception
  {
    jointest();
  }
  
  private static void jointest() throws interruptedexception
  {
    thread thread = new thread()
    {
      public void run()
      {
        try
        {
          for(int i = 0; i < 5; i++)
          {
            system.out.println("线程在运行。");
            thread.sleep(1000);
          }
        }
        catch(interruptedexception ex)
        {
          ex.printstacktrace();
        }
      }
    };
    thread.setdaemon(true);
    thread.start();
    thread.sleep(1000);
    thread.join();
    system.out.println("主线程正常结束。");
  }
}

  我们可以试着将thread.join();注释或者删除,再次运行程序,就可以发现不同了。

  线程间通信

  我们知道,一个进程下面的所有线程是共享内存空间的,那么我们如何在不同的线程之间传递消息呢?在回顾 java i/o时,我们谈到了pipedstream和pipedreader,这里,就是它们发挥作用的地方了。

  下面的两个示例,功能完全一样,不同的是一个使用stream,一个使用reader/writer。

pipeinputstream/pipedoutpuestream 示例
public static void communicationtest() throws ioexception, interruptedexception
{
  final pipedoutputstream pos = new pipedoutputstream();
  final pipedinputstream pis = new pipedinputstream(pos);
  
  thread thread1 = new thread()
  {
    public void run()
    {
      bufferedreader br = new bufferedreader(new inputstreamreader(system.in));
      try
      {
        while(true)
        {
          string message = br.readline();
          pos.write(message.getbytes());
          if (message.equals("end")) break;
        }
        br.close();
        pos.close();
      }
      catch(exception ex)
      {
        ex.printstacktrace();
      }
    }
  };
  
  thread thread2 = new thread()
  {
    public void run()
    {
      byte[] buffer = new byte[1024];
      int bytesread = 0;
      try
      {
        while((bytesread = pis.read(buffer, 0, buffer.length)) != -1)
        {
          system.out.println(new string(buffer));
          if (new string(buffer).equals("end")) break;
          buffer = null;
          buffer = new byte[1024];
        }
        pis.close();
        buffer = null;
      }
      catch(exception ex)
      {
        ex.printstacktrace();
      }
    }
  };
  
  thread1.setdaemon(true);
  thread2.setdaemon(true);
  thread1.start();
  thread2.start();
  thread1.join();
  thread2.join();
}


pipedreader/pipedwriter 示例
private static void communicationtest2() throws interruptedexception, ioexception
{
  final pipedwriter pw = new pipedwriter();
  final pipedreader pr = new pipedreader(pw);
  final bufferedwriter bw = new bufferedwriter(pw);
  final bufferedreader br = new bufferedreader(pr);
  
  thread thread1 = new thread()
  {
    public void run()
    {
      
      bufferedreader br = new bufferedreader(new inputstreamreader(system.in));
      try
      {
        while(true)
        {
          string message = br.readline();
          bw.write(message);
          bw.newline();
          bw.flush();
          if (message.equals("end")) break;
        }
        br.close();
        pw.close();
        bw.close();
      }
      catch(exception ex)
      {
        ex.printstacktrace();
      }
    }
  };
  
  thread thread2 = new thread()
  {
    public void run()
    {
      
      string line = null;
      try
      {
        while((line = br.readline()) != null)
        {
          system.out.println(line);
          if (line.equals("end")) break;
        }
        br.close();
        pr.close();
      }
      catch(exception ex)
      {
        ex.printstacktrace();
      }
    }
  };
  
  thread1.setdaemon(true);
  thread2.setdaemon(true);
  thread1.start();
  thread2.start();
  thread1.join();
  thread2.join();
}

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网