几道有意思的多线程作业题

原作业链接地址
今天先写第二题,如下:

Reverse hello
Write a program called ReverseHello.java that creates a thread (let’s call it Thread 1). Thread 1 creates another thread (Thread 2); Thread 2 creates Thread 3; and so on, up to Thread 50. Each thread should print “Hello from Thread !”, but you should structure your program such that the threads print their greetings in reverse order.

题目大意是,线程1内创建线程2,线程2内创建线程3,…,一直创建到线程50,然后从线程50到线程1依次输出reverse hello . 有点像递归。(╯﹏╰)
这样,线程1必须等待线程2执行完毕,才能执行System.out.print。想到了什么,join()啊!!!
抽象出来的话,就是run()函数中,创建一个新的线程,然后输出”reverse hello”。需要维护一个全局的变量来作为线程的序号。
代码如下:

public class ReverseHello implements Runnable {
    private static volatile int seq = 1;

    @Override
    public void run() {
        if (seq <= 50) {
            Thread r = new Thread(new ReverseHello(), "Thread" + (seq++));
            r.start();
            try {
                r.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("hello from " + Thread.currentThread().getName());
    }

    public static void main(String[] args) {
        new Thread(new ReverseHello(), "Thread" + seq++).start();
    }
}

那么下面问题来了,
1. 为什么要加volatile?
因为线程执行的时候,会把从main memory中的数据读取到自己的线程 local memory中,然后在local memory 中操作数据(读和写),然后在适时写到main memory中,所以,其他线程读取main memory 的时候,可能不是最新的数据。而volatile 则能保证,可以实时的写入main memory 保证main memory 中的数据是最新的。(这个我不太确定,也有说直接操作main memory的)如下:

Declaration of a volatile variable means that the value referred by this variable will never be cached thread local memory, and all operations(read/write) will go to the value in the main memory directly.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值