栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

学习Java第23天笔记

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

学习Java第23天笔记

day23文字笔记
1.什么是线程?
一条线程就是一组任务执行序列
2.什么是多线程?
多线程就是在某一个时间段并发多个任务执行序列
3.为什么需要多线程?
多线程可以“同时”运行多个任务,有效利用资源,让使用者有更好的使用体验
由于硬件决定了多个代码片段不是真正意义上的同时执行,只是模拟这样的操作,实际上多个代码片段都是走走停停的,
但是感官上是同时运行这种执行方式称为“并发”

4.如何创建多线程?

第一种方式:
public class ThreadDemo1 {
public static void main(String[] args) {
Thread t1 = new MyThread1();
Thread t2 = new MyThread2();

public class ThreadDemo2 {
public static void main(String[] args) {
//创建任务实例
Runnable r1 = new MyRunnable1();
Runnable r2 = new MyRunnable2();
//创建线程
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);

    t1.start();
    t2.start();
}

}
class MyRunnable1 implements Runnable{
public void run(){
for (int i =0;i<=1000;i++){
System.out.println(“你是谁啊”);
}
}
}
class MyRunnable2 implements Runnable{
public void run(){
for (int i =0;i<=1000;i++){
System.out.println(“我是查水表的”);
}
}
}
案例:
public class ThreadDemo3 {
public static void main(String[] args) {
//第一种方式:继承Thread重写run方法
Thread t1 = new Thread(() -> {
for (int i =0;i<=1000;i++){
System.out.println(“你是谁啊”);
}
});

    Runnable r2 = new Runnable() {
        public void run() {
            for (int i =0;i<1000;i++){
                System.out.println("我是查水表的");
            }
        }
    };

    Thread t2 = new Thread(r2);
    //第二种方式:实现Runnable接口重写run方法单独定义任务
    t1.start();
    t2.start();
}

}
5.分配线程

public class CurrentThreadDemo {
public static void main(String[] args) {
//获取主线程
Thread main = Thread.currentThread();
System.out.println(“主线程:”+main);
dosome();
System.out.println(“main方法执行完了,”+main+“执行完毕了”);
}
private static void dosome() {
Thread t = Thread.currentThread();
System.out.println(“执行dosome方法的线程是”+t);
}

}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/424956.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号