线程经典问题:先输出10 个hello,然后是10 个world,不希望交替输出hello和world,有哪些解决办法?

【一】题目要求:

先输出10 个hello,然后是10 个world,不希望交替输出hello和world

【二】样例输出:

或着

方法一:使用join()--->具有延迟的作用,适用固定的顺序。

public class Example extends Thread {
        private String data;
        public Example(String data) {
            this.data = data;
        }
        public void run() {
                for (int i = 0; i < 10; i++) {
                    try {
                        Thread.sleep((int) (Math.random() * 1000));
                    } catch (Exception e) {
                    }
                    System.out.print(data+" " );
                }
            System.out.println();
            }

        public static void main(String args[]) throws InterruptedException {
            Thread t1 = new Example("hello");
            Thread t2 = new Example("world");
            t1.start();
            t1.join();//等待t1执行完毕,在执行t2
            t2.start();
        }
    }

方法二:使用synchronized()--->上锁,当一个线程运行完之后,再运行另一个线程,但是两个线程的前后顺序不确定。

public class Example extends Thread {
    private String data;

    public Example(String data) {
        this.data = data;
    }
    public void run() {
        synchronized (Example.class) {
            for (int i = 0; i < 10; i++) {
                try {
                    Thread.sleep((int) (Math.random() * 1000));
                } catch (Exception e) {
                }
                System.out.print(data+" ");
            }
            System.out.println();
        }

    }

    public static void main(String args[]) throws InterruptedException {
        Thread t1 = new Example("hello");
        Thread t2 = new Example("world");
        t1.start();
        t2.start();
    }
}

在使用synchronized()的时候,我犯了一个错误,我在synchronized()中锁住的对象为data,得到的结果都是hello和world交错出现的。后来发现自己锁的对象有问题,因为t1和t2的共同对象不是data,而是Example.class这个类。

日常鸡汤:不轻易用过去来衡量生活的幸与不幸,每个人的生命都可以绽放美丽,只要你珍惜。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值