java25.线程------常用方法

1.取得线程名称

getName();

2.取得当前线程对象

currentThread();

3.判断线程是否启动

isAlive();

4.线程的强行运行

join();

示例:

class RunnableDemo implements Runnable {

    private String name;

    public RunnableDemo(String name) {
        this.name = name;
    }

    public void run() {
        for (int i = 0; i < 100; i++) {
            // 打印出当前线程对象的名称
            // System.out.println("当前线程对象:" + Thread.currentThread().getName());
            System.out.println(name + ":" + i);
        }
    }

}

public class ThreadDemo03 {

    public static void main(String[] args) {
        RunnableDemo r = new RunnableDemo("A");
        Thread t = new Thread(r);
        // 判断线程是否启动
        // System.out.println(t.isAlive());//启动前为false
        t.start();
        // System.out.println(t.isAlive());//启动后为true
        for (int i = 0; i < 50; i++) {// 主线程运行到i>10时,刺激线程t强行执行
            if (i > 10) {
                try {
                    t.join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("主线程" + i);
        }
    }

}

5.线程的休眠

sleep()
.
.
示例:

class RunnableDemo implements Runnable {

    private String name;

    public RunnableDemo(String name) {
        this.name = name;
    }

    public void run() {
        for (int i = 0; i < 100; i++) {
            try {
                Thread.sleep(1000);
                System.out.println(name + ":" + i);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}

public class ThreadDemo03 {

    public static void main(String[] args) {
        RunnableDemo r = new RunnableDemo("A");
        Thread t = new Thread(r);
        t.start();

    }

}

结果:
每秒钟显示一行数据

6.线程的礼让

示例:

class RunnableDemo implements Runnable {

    private String name;

    public RunnableDemo(String name) {
        this.name = name;
    }

    public void run() {
        for (int i = 0; i < 50; i++) {
            System.out.println(name + ":" + i);
            if (i==10) {
                System.out.println("礼让");
                Thread.yield();// 礼让方法
            }
        }
    }

}

public class ThreadDemo03 {

    public static void main(String[] args) {
        RunnableDemo r1 = new RunnableDemo("A");
        RunnableDemo r2 = new RunnableDemo("B");
        Thread t1 = new Thread(r1);
        Thread t2 = new Thread(r2);
        t1.start();
        t2.start();
    }

}

结果:
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值