Java教程 专题
专题目录
您的位置:java > Java教程专题 > Java 多线程编程
Java 多线程编程
作者:--    发布时间:2019-11-20

java给多线程编程提供了内置的支持。一个多线程程序包含两个或多个能并发运行的部分。程序的每一部分都称作一个线程,并且每个线程定义了一个独立的执行路径。

多线程是多任务的一种特别的形式。多线程比多任务需要更小的开销。

这里定义和线程相关的另一个术语:进程:一个进程包括由操作系统分配的内存空间,包含一个或多个线程。一个线程不能独立的存在,它必须是进程的一部分。一个进程一直运行,直到所有的非守候线程都结束运行后才能结束。

多线程能满足程序员编写非常有效率的程序来达到充分利用cpu的目的,因为cpu的空闲时间能够保持在最低限度。


一个线程的生命周期

线程经过其生命周期的各个阶段。下图显示了一个线程完整的生命周期。

线程 

  • 新建状态: 一个新产生的线程从新状态开始了它的生命周期。它保持这个状态直到程序start这个线程。

  • 运行状态:当一个新状态的线程被start以后,线程就变成可运行状态,一个线程在此状态下被认为是开始执行其任务

  • 就绪状态:当一个线程等待另外一个线程执行一个任务的时候,该线程就进入就绪状态。当另一个线程给就绪状态的线程发送信号时,该线程才重新切换到运行状态。

  • 休眠状态: 由于一个线程的时间片用完了,该线程从运行状态进入休眠状态。当时间间隔到期或者等待的事件发生了,该状态的线程切换到运行状态。

  • 终止状态: 一个运行状态的线程完成任务或者其他终止条件发生,该线程就切换到终止状态。


线程的优先级

每一个java线程都有一个优先级,这样有助于操作系统确定线程的调度顺序。java优先级在min_priority(1)和max_priority(10)之间的范围内。默认情况下,每一个线程都会分配一个优先级norm_priority(5)。

具有较高优先级的线程对程序更重要,并且应该在低优先级的线程之前分配处理器时间。然而,线程优先级不能保证线程执行的顺序,而且非常依赖于平台。


创建一个线程

java提供了三种创建线程方法:

  • 通过实现runnable接口;

  • 通过继承thread类本身;

  • 通过 callable 和 future 创建线程。


通过实现runnable接口来创建线程

创建一个线程,最简单的方法是创建一个实现runnable接口的类。

为了实现runnable,一个类只需要执行一个方法调用run(),声明如下:

public void run()

你可以重写该方法,重要的是理解的run()可以调用其他方法,使用其他类,并声明变量,就像主线程一样。

在创建一个实现runnable接口的类之后,你可以在类中实例化一个线程对象。

thread定义了几个构造方法,下面的这个是我们经常使用的:

thread(runnable threadob,string threadname);

这里,threadob 是一个实现runnable 接口的类的实例,并且 threadname指定新线程的名字。

新线程创建之后,你调用它的start()方法它才会运行。

void start();

实例

下面是一个创建线程并开始让它执行的实例:

// 创建一个新的线程
class newthread implements runnable {
   thread t;
   newthread() {
      // 创建第二个新线程
      t = new thread(this, "demo thread");
      system.out.println("child thread: " + t);
      t.start(); // 开始线程
   }
  
   // 第二个线程入口
   public void run() {
      try {
         for(int i = 5; i > 0; i--) {
            system.out.println("child thread: " + i);
            // 暂停线程
            thread.sleep(50);
         }
     } catch (interruptedexception e) {
         system.out.println("child interrupted.");
     }
     system.out.println("exiting child thread.");
   }
}
 
public class threaddemo {
   public static void main(string args[]) {
      new newthread(); // 创建一个新线程
      try {
         for(int i = 5; i > 0; i--) {
           system.out.println("main thread: " + i);
           thread.sleep(100);
         }
      } catch (interruptedexception e) {
         system.out.println("main thread interrupted.");
      }
      system.out.println("main thread exiting.");
   }
}

编译以上程序运行结果如下:

child thread: thread[demo thread,5,main]
main thread: 5
child thread: 5
child thread: 4
main thread: 4
child thread: 3
child thread: 2
main thread: 3
child thread: 1
exiting child thread.
main thread: 2
main thread: 1
main thread exiting.

通过继承thread来创建线程

创建一个线程的第二种方法是创建一个新的类,该类继承thread类,然后创建一个该类的实例。

继承类必须重写run()方法,该方法是新线程的入口点。它也必须调用start()方法才能执行。该方法尽管被列为一种多线程实现方式,但是本质上也是实现了 runnable 接口的一个实例。

实例

// 通过继承 thread 创建线程
class newthread extends thread {
   newthread() {
      // 创建第二个新线程
      super("demo thread");
      system.out.println("child thread: " + this);
      start(); // 开始线程
   }
 
   // 第二个线程入口
   public void run() {
      try {
         for(int i = 5; i > 0; i--) {
            system.out.println("child thread: " + i);
                            // 让线程休眠一会
            thread.sleep(50);
         }
      } catch (interruptedexception e) {
         system.out.println("child interrupted.");
      }
      system.out.println("exiting child thread.");
   }
}
 
public class extendthread {
   public static void main(string args[]) {
      new newthread(); // 创建一个新线程
      try {
         for(int i = 5; i > 0; i--) {
            system.out.println("main thread: " + i);
            thread.sleep(100);
         }
      } catch (interruptedexception e) {
         system.out.println("main thread interrupted.");
      }
      system.out.println("main thread exiting.");
   }
}

编译以上程序运行结果如下:

child thread: thread[demo thread,5,main]
main thread: 5
child thread: 5
child thread: 4
main thread: 4
child thread: 3
child thread: 2
main thread: 3
child thread: 1
exiting child thread.
main thread: 2
main thread: 1
main thread exiting.

thread 方法

下表列出了thread类的一些重要方法:

序号 方法描述
1 public void start()
使该线程开始执行;java 虚拟机调用该线程的 run 方法。
2 public void run()
如果该线程是使用独立的 runnable 运行对象构造的,则调用该 runnable 对象的 run 方法;否则,该方法不执行任何操作并返回。
3 public final void setname(string name)
改变线程名称,使之与参数 name 相同。
4 public final void setpriority(int priority)
 更改线程的优先级。
5 public final void setdaemon(boolean on)
将该线程标记为守护线程或用户线程。
6 public final void join(long millisec)
等待该线程终止的时间最长为 millis 毫秒。
7 public void interrupt()
中断线程。
8 public final boolean isalive()
测试线程是否处于活动状态。

测试线程是否处于活动状态。 上述方法是被thread对象调用的。下面的方法是thread类的静态方法。

序号 方法描述
1 public static void yield()
暂停当前正在执行的线程对象,并执行其他线程。
2 public static void sleep(long millisec)
在指定的毫秒数内让当前正在执行的线程休眠(暂停执行),此操作受到系统计时器和调度程序精度和准确性的影响。
3 public static boolean holdslock(object x)
当且仅当当前线程在指定的对象上保持监视器锁时,才返回 true。
4 public static thread currentthread()
返回对当前正在执行的线程对象的引用。
5 public static void dumpstack()
将当前线程的堆栈跟踪打印至标准错误流。

实例

如下的threadclassdemo 程序演示了thread类的一些方法:

// 文件名 : displaymessage.java
// 通过实现 runnable 接口创建线程
public class displaymessage implements runnable
{
   private string message;
   public displaymessage(string message)
   {
      this.message = message;
   }
   public void run()
   {
      while(true)
      {
         system.out.println(message);
      }
   }
}

guessanumber.java 文件代码:

// 文件名 : guessanumber.java
// 通过继承 thread 类创建线程

public class guessanumber extends thread
{
   private int number;
   public guessanumber(int number)
   {
      this.number = number;
   }
   public void run()
   {
      int counter = 0;
      int guess = 0;
      do
      {
          guess = (int) (math.random() * 100 + 1);
          system.out.println(this.getname()
                       + " guesses " + guess);
          counter++;
      }while(guess != number);
      system.out.println("** correct! " + this.getname()
                       + " in " + counter + " guesses.**");
   }
}

threadclassdemo.java 文件代码:

// 文件名 : threadclassdemo.java
public class threadclassdemo
{
   public static void main(string [] args)
   {
      runnable hello = new displaymessage("hello");
      thread thread1 = new thread(hello);
      thread1.setdaemon(true);
      thread1.setname("hello");
      system.out.println("starting hello thread...");
      thread1.start();
     
      runnable bye = new displaymessage("goodbye");
      thread thread2 = new thread(bye);
      thread2.setpriority(thread.min_priority);
      thread2.setdaemon(true);
      system.out.println("starting goodbye thread...");
      thread2.start();
 
      system.out.println("starting thread3...");
      thread thread3 = new guessanumber(27);
      thread3.start();
      try
      {
         thread3.join();
      }catch(interruptedexception e)
      {
         system.out.println("thread interrupted.");
      }
      system.out.println("starting thread4...");
      thread thread4 = new guessanumber(75);
     
           thread4.start();
      system.out.println("main() is ending...");
   }
}

运行结果如下,每一次运行的结果都不一样。

starting hello thread...
starting goodbye thread...
hello
hello
hello
hello
hello
hello
hello
hello
hello
starting thread3...
hello
hello
starting thread4...
hello
hello
main() is ending...

通过 callable 和 future 创建线程

  • 1. 创建 callable 接口的实现类,并实现 call() 方法,该 call() 方法将作为线程执行体,并且有返回值。
  • 2. 创建 callable 实现类的实例,使用 futuretask 类来包装 callable 对象,该 futuretask 对象封装了该 callable 对象的 call() 方法的返回值。
  • 3. 使用 futuretask 对象作为 thread 对象的 target 创建并启动新线程。
  • 4. 调用 futuretask 对象的 get() 方法来获得子线程执行结束后的返回值。

实例

public class callablethreadtest implements callable<integer> {
    public static void main(string[] args)  
    {  
        callablethreadtest ctt = new callablethreadtest();  
        futuretask<integer> ft = new futuretask<>(ctt);  
        for(int i = 0;i < 100;i++)  
        {  
            system.out.println(thread.currentthread().getname()+" 的循环变量i的值"+i);  
            if(i==20)  
            {  
                new thread(ft,"有返回值的线程").start();  
            }  
        }  
        try  
        {  
            system.out.println("子线程的返回值:"+ft.get());  
        } catch (interruptedexception e)  
        {  
            e.printstacktrace();  
        } catch (executionexception e)  
        {  
            e.printstacktrace();  
        }  
  
    }
    @override  
    public integer call() throws exception  
    {  
        int i = 0;  
        for(;i<100;i++)  
        {  
            system.out.println(thread.currentthread().getname()+" "+i);  
        }  
        return i;  
    }  
}

创建线程的三种方式的对比

  • 1. 采用实现 runnable、callable 接口的方式创建多线程时,线程类只是实现了 runnable 接口或 callable 接口,还可以继承其他类。
  • 2. 使用继承 thread 类的方式创建多线程时,编写简单,如果需要访问当前线程,则无需使用 thread.currentthread() 方法,直接使用 this 即可获得当前线程。

线程的几个主要概念

在多线程编程时,你需要了解以下几个概念:

  • 线程同步

  • 线程间通信

  • 线程死锁

  • 线程控制:挂起、停止和恢复


多线程的使用

有效利用多线程的关键是理解程序是并发执行而不是串行执行的。例如:程序中有两个子系统需要并发执行,这时候就需要利用多线程编程。

通过对多线程的使用,可以编写出非常高效的程序。不过请注意,如果你创建太多的线程,程序执行的效率实际上是降低了,而不是提升了。

请记住,上下文的切换开销也很重要,如果你创建了太多的线程,cpu花费在上下文的切换的时间将多于执行程序的时间!


网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册