多线程

作者: 魔女小姐的猫 | 来源:发表于2020-07-02 07:02 被阅读0次

进程

在多任务的系统中,每个独立执行的程序都被称为进程(正在进行的程序)
CPU只有一个的情况下,每个进程之间要不断的切换,反而要额外的开销(交替执行多个程序)反而更慢
双CPU系统才能实现多进程,每个CPU一个执行一个程序,两个程序同时进行
一个进程可以包含一个或多个线程

线程

一个线程就是一个程序内部的一条执行线索
多线程:一个程序实现多段代码同时交替运行,就需要产生多个线程,并且指定每个线程要执行的代码   
Thread.currentThread().getName();

Thread thread = new Thread();
//后台线程
thread.setDaemon(true);

多线程卖票案例

public class ThreadDemo {
    public static void main(String[] args) {
        try {
            /**
             * 一个thread对象是一个线程
             */
            TestThread tt = new TestThread();
            // 继承thread
            // tt.start();
            // tt.start();
            // tt.start();
            // tt.start();

            new Thread(tt).start();
            new Thread(tt).start();
            new Thread(tt).start();
            new Thread(tt).start();
        } catch (Exception e) {
            // TODO: handle exception
        }
    }
}

/**
 * 实现runnable 接口比继承thread灵活
 * 
 * 适合多个相同程序代码的线程去处理同一资源的情况,把虚拟CPU(线程)同程序代码、数据有效分离 , 体现了面向对象的设计思想
 * 
 * @author TianYu
 *
 */
class TestThread implements Runnable /* extends Thread */ {
    int tickets = 100;

    @Override
    public void run() {
        while (true) {
            if (tickets > 0) {
                System.out.println(Thread.currentThread().getName() + "  is show " + tickets--);
            }
        }
    }
}

相关文章

  • iOS多线程 NSOperation

    系列文章: 多线程 多线程 pthread、NSThread 多线程 GCD 多线程 NSOperation 多线...

  • iOS多线程 pthread、NSThread

    系列文章: 多线程 多线程 pthread、NSThread 多线程 GCD 多线程 NSOperation 多线...

  • iOS多线程: GCD

    系列文章: 多线程 多线程 pthread、NSThread 多线程 GCD 多线程 NSOperation 多线...

  • iOS多线程运用

    系列文章: 多线程 多线程 pthread、NSThread 多线程 GCD 多线程 NSOperation 多线...

  • iOS多线程基础

    系列文章: 多线程 多线程 pthread、NSThread 多线程 GCD 多线程 NSOperation 多线...

  • 多线程介绍

    一、进程与线程 进程介绍 线程介绍 线程的串行 二、多线程 多线程介绍 多线程原理 多线程的优缺点 多线程优点: ...

  • iOS进阶之多线程管理(GCD、RunLoop、pthread、

    深入理解RunLoopiOS多线程--彻底学会多线程之『GCD』iOS多线程--彻底学会多线程之『pthread、...

  • iOS多线程相关面试题

    iOS多线程demo iOS多线程之--NSThread iOS多线程之--GCD详解 iOS多线程之--NSOp...

  • 多线程之--NSOperation

    iOS多线程demo iOS多线程之--NSThread iOS多线程之--GCD详解 iOS多线程之--NSOp...

  • iOS多线程之--NSThread

    iOS多线程demo iOS多线程之--NSThread iOS多线程之--GCD详解 iOS多线程之--NSOp...

网友评论

      本文标题:多线程

      本文链接:https://www.haomeiwen.com/subject/jyflqktx.html