java多线程

本文通过具体示例展示了Java中多线程的创建与启动方式,包括通过继承Thread类及实现Runnable接口两种方法,并演示了如何设置线程名称及简单的线程调度。

奉天承运,博主诏曰:

多线程

在这里插入图片描述

主线程

在这里插入图片描述

线程的创建和启动

在这里插入图片描述

代码演示

public class TestThread extends Thread{
    public void run(){//线程工作的主体,重写run方法实现
        Thread t=Thread.currentThread();
        for (int i = 0; i < 10; i++) {
            System.out.println(t.getName()+":第"+(i+1)+"次执行");
        }
    }

    public static void main(String[] args) {
        TestThread t1=new TestThread();
//        TestThread t2=new TestThread();
        Thread th1=new Thread(t1,"线程1");
        Thread th2=new Thread(t1,"线程2");
//        t1.setName("线程1");
//        t2.setName("线程2");
//        t1.run();
//        t2.run();
        th1.start();
        th2.start();//使用start方法才是真正意义上的java多线程
    }
}
public class TestRunable implements Runnable{
    @Override
    public void run() {
        Thread t=Thread.currentThread();
        for (int i = 0; i < 10; i++) {
            System.out.println(t.getName()+":第"+(i+1)+"次执行");
//            try {
//                Thread.sleep(1000);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
        }
    }

    public static void main(String[] args) {
        TestRunable tr=new TestRunable();
        Thread t1=new Thread(tr,"接口线程一");
        Thread t2=new Thread(tr,"接口线程二");
//        t1.setPriority(1);//优先级
//        t2.setPriority(10);
        t1.start();
        t2.start();
        for (int i = 1; i <=10 ; i++) {
            System.out.println(Thread.currentThread().getName()+"运行第"+i+"次");
            if(i%3==0){
                Thread.yield();//线程礼让并没什么用
//                try {
//                    t1.join(10);//如果join的线程join前一直是阻塞状态
//                    //则等待参数里的毫秒数,超时则不继续等待,被join的线程继续运行
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
            }
        }
    }
}

钦此。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值