Java学习之多线程

  • 测试Thread中的常用方法
  • 1.stat();启动当前线程,并调用当前线程的run()
  • 2.run();
  • 3.currentcThread();静态方法,返回执行当前代码的线程
  • 4.getName();
  • 5.setName();
  • 6.yield();释放当cpu的执行权,有可能还是当前的获取
  • 7.join();分线程加入,执行完后,主线程才执行。当主线程需要分线程执行完的数据时使用。
  • a中调用b的join,此时a进入阻塞状态,知道b执行完。
  • 8.stop();deprecated 不建议使用,过时。
  • 9.sleep();阻塞时间为ms
    1. isAlive;判断线程是否存活
  • 线程的优先级:
  • MAX_PRIORITY:10 最高
  • MIN_PRIORITY:1 最低
  • NORM_PRIORITY:5 普通
  • 高优先级要抢占低优先级的线程,只是概率上的高,不是绝对的高优先级全部执行完后,低优先级才执行
  • getPriority() 获取优先级
  • setPriority() 设置优先级

下面展示一些 内联代码片

// A code block
var foo = 'bar';
// An highlighted block

class MThread extends Thread {
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            if (i % 2 == 0) {
                try {
                    sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + i + getPriority() + "副线程");
            }
            if (i % 20 == 0) {
                yield();
            }
        }
    }
}

public class ThreadMethodTest {
    public static void main(String[] args) {
        MThread t1 = new MThread();
        t1.setPriority(Thread.MAX_PRIORITY);
        t1.start();//启动当前线程,调用当前线程的run方法
//        t1.run(); //只调用方法,不是多线程
        System.out.println("thread test");
        for (int i = 0; i < 100; i++) {
            if (i % 2 == 0) {
                System.out.println(Thread.currentThread().getName() + i + Thread.currentThread().getPriority() + "**********主线程**********");
            }
            if (i == 20) {
                try {
                    t1.join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println(t1.isAlive());
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值