Java多线程学习笔记(1)

使用多线程
学习一项技术就要去使用它

package test;
public class Test {
public static void main(String[] args) {
    System.out.println(Thread.currentThread().getName());
}
}

main
如上就是输出了一个叫main的线程,而跟main方法名没有关系。

继承Thread类
package com.mythread.www;

public class MyThread extends Thread {
    @Override
    public void run() {
        // TODO Auto-generated method stub
        super.run();
        System.out.println("MyThread");
    }
}
运行类如下:
package com.mythread.www.thread;

import com.mythread.www.MyThread;

public class Run {
public static void main(String[] args) {
    MyThread mythread=new MyThread();
    mythread.start();
    System.out.println("运行结束");
}
}

运行结束
MyThread
从运行结果来看,run中的执行方法比较晚,这也就是说运行结果与代码顺序无关。
线程是一个子任务,CPU不确定的方法,或者说是以随机的时间来调用线程的方法run

创建自定义线程

package mythread;

public class MyThread extends Thread {
    @Override
    public void run() {
        // TODO Auto-generated method stub
        super.run();

        try {
            for (int i = 0; i < 10; i++) {
                int time = (int) (Math.random() * 1000);
                Thread.sleep(time);
                System.out.println("run="+Thread.currentThread().getName());
            }
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}
运行类:
package test;

import mythread.MyThread;

public class Test2 {
    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.setName("myThread");
        thread.start();
    for (int i = 0; i <10; i++) {
        int time=(int)(Math.random()*1000);
        try {
            Thread.sleep(time);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("main="+Thread.currentThread().getName());
    }

    }
}

main=main
run=myThread
main=main
run=myThread
main=main
run=myThread
main=main
main=main
run=myThread
run=myThread
run=myThread
main=main
main=main
run=myThread
main=main
run=myThread
main=main
run=myThread
main=main
run=myThread

Thread.java类中的start()方法通知“线程规划器”此线程已经准备就绪,等待调用,等待调用线程对象的run()方法。这个过程其实就是让系统安排一个时间来调用Thread中的run()方法,也就是使线程得到运行,启动线程,具有异步执行的结果。如果调用代码thread.run()就不是异步执行了,而是同步,那么此线程对象并不交给“线程规划器”来处理,而是由main主线程来调用run()方法,也就是必须等run()方法中的代码执行完才可以执行后面的代码。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

sunywz

~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值