选择两个城市作为预选旅目标。(创建线程的两种方式)

选择两个城市作为预选旅目标。实现两个独立的线程分别显示10次城市名,每次显示后休眠一段随机的时间(1000ms以内),哪个先显示完毕,就决定去哪个城市。(用两种方式实现)(修改线程的优先级,再测试结果。)

1.通过继承Thread类创建线程

2.通过向Thread()构造方法传递Runnable对象来创建线程

import java.util.Random;



class MyThread extends Thread{
	String cityName;
	public MyThread(String name) {
		this.cityName = name;
	}
	//定义一个随机种子 因为线程休眠随机的时间
	Random rand = new Random();
	public void run() {
		int r = rand.nextInt(1000);//1000是生成随机数的上限(题目要求休眠一段随机的时间),下限为0
		for(int i = 0;i <10;i++) {
		System.out.println(i + 1 +":"+ cityName);
		try {
			Thread.sleep(r);
		}catch(InterruptedException e) {
			 e.printStackTrace();
		}
		if(i == 9) {
			System.out.println("我决定去" + cityName);
			System.exit(0);
		}
		}
	}
}
class MyRunnable implements Runnable{
	Random rand = new Random();
	public void run() {
		int r = rand.nextInt(1000);//1000是生成随机数的上限(题目要求休眠一段随机的时间),下限为0
		for(int i = 0;i <10;i++) {
		System.out.println(i + 1 + ":" + Thread.currentThread().getName());
		try {
			Thread.sleep(r);
		}catch(InterruptedException e) {
			e.printStackTrace();
		}
		if(i == 9) {
			System.out.println("我决定去" + Thread.currentThread().getName());
			System.exit(0);
		 } 
		}
   }
} 
public class Test{
	public static void main(String[] args) {
//		System.out.println("测试MyThread线程:");
//		MyThread t1 = new MyThread("挪威");
//		t1.start();
//		MyThread t2 = new MyThread("北海道");
//		t2.start();
		
//		System.out.println("测试MyRunnable线程:");
//		MyRunnable runnable = new MyRunnable();
//		Thread  t1 = new Thread(runnable,"挪威");
//		t1.start();
//		MyRunnable runnable1 = new MyRunnable();
//		Thread  t2 = new Thread(runnable1,"北海道");
//		t2.start();
//		
//		
//		MyRunnable runnable2 = new MyRunnable();
//		Thread  t3 = new Thread(runnable2,"北京");
//		t3.start();
		System.out.println("设定不同的优先级:");
		MyRunnable runnable = new MyRunnable();
		Thread  t1 = new Thread(runnable,"挪威");
		MyRunnable runnable1 = new MyRunnable();
		Thread  t2 = new Thread(runnable1,"北海道");
		
		t1.setPriority(Thread.MAX_PRIORITY);
		t2.setPriority(Thread.MIN_PRIORITY);
		t1.start();
		t2.start();
		
//		MyRunnable runnable2 = new MyRunnable();
//		Thread  t3 = new Thread(runnable2,"北京");
//		t3.setPriority(Thread.NORM_PRIORITY);
//		t3.start();
		
	}
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值