zoukankan      html  css  js  c++  java
  • 1:进程与线程概述

    进程:进程可以理解为操作系统管理的基本运行单元。ie浏览器是一个进程,word是一个进程,正在操作系统中运行的“.exe"也可以理解为一个进程。

    线程:进程中独立运行的子任务就是一个线程。像qq.exe运行的时候有很多子任务比如聊天线程、好友视频线程、下载文件线程等等。

    使用多线程的优势:

    1.发挥多处理器的强大能力

    2.在单处理器系统上获得更高的吞吐率

    3.建模的简单性

    4.异步事件的简化处理

    创建线程的方式:

    1.继承Thread,重写父类中的run()方法

     1 public class MyThread00 extends Thread
     2 {        
     3     public void run()
     4     {
     5         for (int i = 0; i < 5; i++)
     6         {
     7             System.out.println(Thread.currentThread().getName() + "在运行!");
     8         }
     9     }
    10 }
     1 public static void main(String[] args)
     2 {
     3     MyThread00 mt0 = new MyThread00();
     4     mt0.start();
     5         
     6     for (int i = 0; i < 5; i++)
     7     {
     8         System.out.println(Thread.currentThread().getName() + "在运行!");
     9     }
    10 }

    2.实现Runnable接口。这里再实现Runnable之后,需要新建一个thread来启动。

     1 public class MyThread01 implements Runnable
     2 {
     3     public void run()
     4     {
     5         for (int i = 0; i < 5; i++)
     6         {
     7             System.out.println(Thread.currentThread().getName() + "在运行!");
     8         }
     9     }
    10 }
     1 public static void main(String[] args)
     2 {
     3     MyThread01 mt0 = new MyThread01();
     4     Thread t = new Thread(mt0);
     5     t.start();
     6         
     7     for (int i = 0; i < 5; i++)
     8     {
     9         System.out.println(Thread.currentThread().getName() + "在运行!");
    10     }
    11 }

    两种多线程实现方式的对比

    看一下Thread类的API:

    (1)继承Thread类其实最终也是实现了Runnable接口。

    (2)继承只能单继承,实现可以多实现。

    (3)实现的方式对比继承的方式,也有利于减小程序之间的耦合。

    因此,多线程的实现几乎都是使用的Runnable接口的方式。不过,后面的文章,为了简单,就用继承Thread类的方式了。

    (原文参考:http://www.cnblogs.com/xrq730/p/4850883.html)

  • 相关阅读:
    python-进程池实例
    python-进程通过队列模拟数据的下载
    python-多进程模板
    python-多线程同步中创建互斥锁解决资源竞争的问题
    CentOS6.5配置网络
    解决CentOS系统Yum出现"Cannot find a valid baseurl for repo"问题
    CentOS 6.5安装图形界面
    Centos安装git
    Web前端优化,提高加载速度
    谁说写代码的不懂生活
  • 原文地址:https://www.cnblogs.com/leehfly/p/4972280.html
Copyright © 2011-2022 走看看