Java多线程编程

来源:互联网 发布:阿里巴巴查排名软件 编辑:程序博客网 时间:2024/05/15 08:30

Java多线程的写法有几种,这里列举其中的两种


1. 通过继承Thread 类定义新线程

public class SubclassThread extends Thread {      public void run() {          while (true) {          // 执行线程自身的任务              try {                  sleep(5 * 1000);                  break;              } catch (InterruptedException exc) {              // 睡眠被中断              }          }      }      public static void main(String[] args) {          Thread thread = new SubclassThread();          thread.start();          System.out.println("主程序结束");      }  }


2. 通过实现Runnable 接口定义新线程
class Counter implements Runnable {      public void run() {          for (int i = 0; i < 100; i++) System.out.println("计数器= " + i);      }  }  public class RunnableThread {      public static void main(String[] args) {          Counter counter = new Counter();          Thread thread = new Thread(counter);          thread.start();          System.out.println("主程序结束");      }  }


在利用Runnable接口定义线程的学习中,笔者还学习了使用线程池的方式来启动线程

import java.util.concurrent.ExecutorService;  import java.util.concurrent.Executors;    class Counter implements Runnable {      public void run() {          for (int i = 0; i < 100; i++) System.out.println("计数器= " + i);      }  }    public class Runner {        public static void main(String[] args) {          ExecutorService application = Executors.newCachedThreadPool(); //申请一个线程池                    application.execute(new Counter()); // 从线程池中运行一个新线程                    application.shutdown(); // 关闭线程池      }    }


优缺点:

Runnable:

优点:节约java宝贵的单继承指标。

缺点:运行时需要构建一个Thread实例来运行或者创建线程池服务来运行实现的Runnable。

Thread:

优点:实现的时候代码较为简单。

缺点:实现需要继承Thread。

0 0
原创粉丝点击