多线程 Thread-1

线程的存在是离不开进程的。进程如果消失线程一定会消失

注意区分线程与进程的概念

1.多线程的实现(Thread实现)

package cn.ls.xiancheng;

public class MyThread extends Thread {
    private String name;
    public MyThread(String name) {
        this.name=name;
    }
    @Override
    public void run() {
        for(int x=0;x<10;x++) {
            System.out.println(this.name +"-->"+x);
        }
    }
    public static void main(String[] args) {
        MyThread mt1=new MyThread("线程一");
        MyThread mt2=new MyThread("线程二");
        MyThread mt3=new MyThread("线程三");
        mt1.start();
        mt2.start();
        mt3.start();
    }
}

这里为什么多线程的启动时start而不是run?
先来看看源代码:

    public synchronized void start() {
        /**
         * This method is not invoked for the main method thread or "system"
         * group threads created/set up by the VM. Any new functionality added
         * to this method in the future may have to also be added to the VM.
         *
         * A zero status value corresponds to state "NEW".
         */
        if (threadStatus != 0)
            throw new IllegalThreadStateException();

        /* Notify the group that this thread is about to be started
         * so that it can be added to the group's list of threads
         * and the group's unstarted count can be decremented. */
        group.add(this);

        boolean started = false;
        try {
            start0();
            started = true;
        } finally {
            try {
                if (!started) {
                    group.threadStartFailed(this);
                }
            } catch (Throwable ignore) {
                /* do nothing. If start0 threw a Throwable then
                  it will be passed up the call stack */
            }
        }
    }

start0();
注意这里有个start方法。这个的作用是根据操作系统的不同去进行资源的分配
所以Thread类的start方法不仅仅要启动多线程的执行代码,还要根据操作系统的不同进行资源的分配

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值