Java并发总结(一)

Java并发总结

一、开启线程

1、Runnalbe接口

新建一个LiftOff.java 文件

public class LiftOff implements Runnable {
  protected int countDown = 10; // Default
  private static int taskCount = 0;
  private final int id = taskCount++;
  public LiftOff() {}
  public LiftOff(int countDown) {
    this.countDown = countDown;
  }
  public String status() {
    return "#" + id + "(" +
      (countDown > 0 ? countDown : "Liftoff!") + "), ";
  }
  public void run() {
    while(countDown-- > 0) {
      System.out.print(status());
      Thread.yield();
    }
  }
}

这里需要注意一下Thread.yield() 方法,使当前线程由执行状态,变成为就绪状态,让出cpu时间,在下一个线程执行时候,此线程有可能被执行,也有可能没有被执行。

然后创建MainThread.java文件

public class MainThread {
  public static void main(String[] args) {
    LiftOff launch = new LiftOff();
    launch.run();
  }
}

点击运行,此时的结果为

#0(9), #0(8), #0(7), #0(6), #0(5), #0(4), #0(3), #0(2), #0(1), #0(Liftoff!), 

2.Thread类开启线程

新建BasicThreads.java的文件

public class BasicThreads {
  public static void main(String[] args) {
    Thread t = new Thread(new LiftOff());
    t.start();
    System.out.println("Waiting for LiftOff");
  }
}

此时运行结果为:

Waiting for LiftOff
#0(9), #0(8), #0(7), #0(6), #0(5), #0(4), #0(3), #0(2), #0(1), #0(Liftoff!), 

3、多线程驱动多任务

新建MoreBasicThreads.java的文件

public class MoreBasicThreads {
  public static void main(String[] args) {
    for(int i = 0; i < 5; i++)
      new Thread(new LiftOff()).start();
    System.out.println("Waiting for LiftOff");
  }
} 

运行结果为:

Waiting for LiftOff
#2(9), #2(8), #2(7), #2(6), #2(5), #3(9), #3(8), #4(9), #1(9), #1(8), #1(7), #1(6), #1(5), #1(4), #1(3), #1(2), #1(1), #0(9), #0(8), #0(7), #0(6), #1(Liftoff!), #4(8), #4(7), #4(6), #4(5), #3(7), #2(4), #2(3), #2(2), #3(6), #4(4), #4(3), #4(2), #4(1), #0(5), #4(Liftoff!), #3(5), #3(4), #3(3), #3(2), #2(1), #3(1), #3(Liftoff!), #0(4), #2(Liftoff!), #0(3), #0(2), #0(1), #0(Liftoff!), 

由输出结果可以看出,不同的任务的执行在线程被换进换出时混在了一起,这种交换时由线程调度器自动控制的。

注意:start()方法的调用后并不是立即执行多线程代码,而是使得该线程变为可运行态(Runnable),什么时候运行是由操作系统决定的。

以上就是Java开启线程的方法,一个使用Thread类,一个使用Runnable接口。

posted @ 2020-11-10 22:39  wangheq  阅读(92)  评论(0编辑  收藏  举报