码迷,mamicode.com
首页 > 编程语言 > 详细

java 线程练习题1

时间:2016-06-03 21:31:53      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:

随便选择两个城市作为预选旅游目标。实现两个独立的线程分别显示10次城市名,每次显示后休眠一段随机时间(1000ms以内),哪个先显示完毕,就决定去哪个城市。分别用Runnable接口和Thread类实现。

package com.hanqi.xiancheng;

import java.util.Random;

public class Test6 implements Runnable {

    Random r = new Random();
    int a = r.nextInt(1000);

    @Override
    public void run() {

        for (int i = 0; i < 10; i++)

        {
            System.out.println(Thread.currentThread().getName());

            try {
                Thread.sleep(a);
            } catch (InterruptedException e) {
                // TODO 自动生成的 catch 块
                e.printStackTrace();
            }
        }

    }

}
package com.hanqi.xiancheng;

import java.util.Random;

public class Test8 extends Thread {

    Random r = new Random();
    int a = r.nextInt(1000);

    @Override
    public void run() {

        for (int i = 0; i < 10; i++)

        {
            System.out.println(Thread.currentThread().getName());

            try {
                Thread.sleep(a);
            } catch (InterruptedException e) {
                // TODO 自动生成的 catch 块
                e.printStackTrace();
            }
        }
    }

}
package com.hanqi.xiancheng;

public class Test7 {

    public static void main(String[] args) {
        // TODO 自动生成的方法存根
        Thread th=new Thread(new Test6());
        th.setName("海南");
        th.start();
        Thread th2=new Thread(new Test6());
        th2.setName("西藏");
        th2.start();

    }
    

}

技术分享

package com.hanqi.xiancheng;

public class Test7 {

    public static void main(String[] args) {
        // TODO 自动生成的方法存根

        Test8 th3=new Test8();
        th3.setName("海南");
        th3.start();
        Test8 th4=new Test8();
        th4.setName("西藏");
        th4.start();
    }
    

}

技术分享

java 线程练习题1

标签:

原文地址:http://www.cnblogs.com/jskbk/p/5557482.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!