java 多线程编程——迹忆客-ag捕鱼王app官网
java 给多线程编程提供了内置的支持。 一条线程指的是进程中一个单一顺序的控制流,一个进程中可以并发多个线程,每条线程并行执行不同的任务。
多线程是多任务的一种特别的形式,但多线程使用了更小的资源开销。
这里定义和线程相关的另一个术语 - 进程:一个进程包括由操作系统分配的内存空间,包含一个或多个线程。一个线程不能独立的存在,它必须是进程的一部分。一个进程一直运行,直到所有的非守护线程都结束运行后才能结束。
多线程能满足程序员编写高效率的程序来达到充分利用 cpu 的目的。
一个线程的生命周期
线程是一个动态执行的过程,它也有一个从产生到死亡的过程。
下图显示了一个线程完整的生命周期。

1. 新建状态:
使用 new 关键字和 thread 类或其子类建立一个线程对象后,该线程对象就处于新建状态。它保持这个状态直到程序 start() 这个线程。
2. 就绪状态:
当线程对象调用了start()方法之后,该线程就进入就绪状态。就绪状态的线程处于就绪队列中,要等待jvm里线程调度器的调度。
3. 运行状态:
如果就绪状态的线程获取 cpu 资源,就可以执行 run(),此时线程便处于运行状态。处于运行状态的线程最为复杂,它可以变为阻塞状态、就绪状态和死亡状态。
4. 阻塞状态:
如果一个线程执行了sleep(睡眠)、suspend(挂起)等方法,失去所占用资源之后,该线程就从运行状态进入阻塞状态。在睡眠时间已到或获得设备资源后可以重新进入就绪状态。可以分为三种:
- 等待阻塞 :运行状态中的线程执行 wait() 方法,使线程进入到等待阻塞状态。
- 同步阻塞 :线程在获取 synchronized 同步锁失败(因为同步锁被其他线程占用)。
- 其他阻塞 :通过调用线程的 sleep() 或 join() 发出了 i/o 请求时,线程就会进入到阻塞状态。当sleep() 状态超时,join() 等待线程终止或超时,或者 i/o 处理完毕,线程重新转入就绪状态。
5. 死亡状态:
一个运行状态的线程完成任务或者其他终止条件发生时,该线程就切换到终止状态。
线程的优先级
每一个 java 线程都有一个优先级,这样有助于操作系统确定线程的调度顺序。
java 线程的优先级是一个整数,其取值范围是 1 (thread.min_priority ) - 10 (thread.max_priority )。
默认情况下,每一个线程都会分配一个优先级 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 runnabledemo implements runnable { private thread t; private string threadname; runnabledemo( string name) { threadname = name; system.out.println("creating " threadname ); } public void run() { system.out.println("running " threadname ); try { for(int i = 4; i > 0; i--) { system.out.println("thread: " threadname ", " i); // 让线程睡眠一会 thread.sleep(50); } }catch (interruptedexception e) { system.out.println("thread " threadname " interrupted."); } system.out.println("thread " threadname " exiting."); } public void start () { system.out.println("starting " threadname ); if (t == null) { t = new thread (this, threadname); t.start (); } } } public class testthread { public static void main(string args[]) { runnabledemo r1 = new runnabledemo( "thread-1"); r1.start(); runnabledemo r2 = new runnabledemo( "thread-2"); r2.start(); } }
编译以上程序运行结果如下:
creating thread-1
starting thread-1
creating thread-2
starting thread-2
running thread-1
thread: thread-1, 4
running thread-2
thread: thread-2, 4
thread: thread-1, 3
thread: thread-2, 3
thread: thread-1, 2
thread: thread-2, 2
thread: thread-1, 1
thread: thread-2, 1
thread thread-1 exiting.
thread thread-2 exiting.
通过继承thread来创建线程
创建一个线程的第二种方法是创建一个新的类,该类继承 thread 类,然后创建一个该类的实例。
继承类必须重写 run() 方法,该方法是新线程的入口点。它也必须调用 start() 方法才能执行。
该方法尽管被列为一种多线程实现方式,但是本质上也是实现了 runnable 接口的一个实例。
实例
class threaddemo extends thread { private thread t; private string threadname; threaddemo( string name) { threadname = name; system.out.println("creating " threadname ); } public void run() { system.out.println("running " threadname ); try { for(int i = 4; i > 0; i--) { system.out.println("thread: " threadname ", " i); // 让线程睡眠一会 thread.sleep(50); } }catch (interruptedexception e) { system.out.println("thread " threadname " interrupted."); } system.out.println("thread " threadname " exiting."); } public void start () { system.out.println("starting " threadname ); if (t == null) { t = new thread (this, threadname); t.start (); } } } public class testthread { public static void main(string args[]) { threaddemo t1 = new threaddemo( "thread-1"); t1.start(); threaddemo t2 = new threaddemo( "thread-2"); t2.start(); } }
编译以上程序运行结果如下:
creating thread-1
starting thread-1
creating thread-2
starting thread-2
running thread-1
thread: thread-1, 4
running thread-2
thread: thread-2, 4
thread: thread-1, 3
thread: thread-2, 3
thread: thread-1, 2
thread: thread-2, 2
thread: thread-1, 1
thread: thread-2, 1
thread thread-1 exiting.
thread thread-2 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 文件代码:
// 文件名 : 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
goodbye
goodbye
goodbye
goodbye
goodbye
.......
通过 callable 和 future 创建线程
- 创建 callable 接口的实现类,并实现 call() 方法,该 call() 方法将作为线程执行体,并且有返回值。
- 创建 callable 实现类的实例,使用 futuretask 类来包装 callable 对象,该 futuretask 对象封装了该 callable 对象的 call() 方法的返回值。
- 使用 futuretask 对象作为 thread 对象的 target 创建并启动新线程。
- 调用 futuretask 对象的 get() 方法来获得子线程执行结束后的返回值。
实例
public class callablethreadtest implements callable
{ public static void main(string[] args) { callablethreadtest ctt = new callablethreadtest(); futuretask 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; } }
创建线程的三种方式的对比
- 采用实现 runnable、callable 接口的方式创建多线程时,线程类只是实现了 runnable 接口或 callable 接口,还可以继承其他类。
- 使用继承 thread 类的方式创建多线程时,编写简单,如果需要访问当前线程,则无需使用 thread.currentthread() 方法,直接使用 this 即可获得当前线程。
线程的几个主要概念
在多线程编程时,你需要了解以下几个概念:
- 线程同步
- 线程间通信
- 线程死锁
- 线程控制:挂起、停止和恢复
多线程的使用
有效利用多线程的关键是理解程序是并发执行而不是串行执行的。例如:程序中有两个子系统需要并发执行,这时候就需要利用多线程编程。
通过对多线程的使用,可以编写出非常高效的程序。不过请注意,如果你创建太多的线程,程序执行的效率实际上是降低了,而不是提升了。
请记住,上下文的切换开销也很重要,如果你创建了太多的线程,cpu 花费在上下文的切换的时间将多于执行程序的时间!