Java面试题:编程题(Thread和Runnable)
【考题题干】创建两个线程,每个线程打印出线程名字后再睡眠,给其他线程以执行的机会,每个线程前后共睡眠5次。最后打印出线程结束信息退出。要求分别采用从Thread中继承和实现Runnable接口两种方式来实现程序(即写两个程序)。
【参考答案】
(1)继承Thread类实现方式
public class BB extends Thread{
int time;
public BB(int t){
time = t;
}
public void run(){
for(int i=1;i<=5;i++){
System.out.println(Thread.currentThread().getName()+" "+i+"次");
try {
Thread.sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(i==5){
System.out.println(Thread.currentThread().getName()+"退出了");
}
}
}
public static void main(String[] args){
BB b1 = new BB(500);
b1.setName("线程1");
b1.start();
BB b2 = new BB(200);
b2.setName("线程2");
b2.start();
BB b3 = new BB(300);
b3.setName("线程3");
b3.start();
}
}
(2)Runnable接口实现方式
public class BB implements Runnable{
private int time;
private Thread th;
public BB(String name,int n){
time = n;
th = new Thread(this,name);
th.start();
}
public void run(){
for(int i=1;i<=5;i++){
System.out.println(Thread.currentThread().getName()+" "+i+"次");
try {
Thread.sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(i==5){
System.out.println(Thread.currentThread().getName()+"退出了");
}
}
}
public static void main(String[] args){
BB b1 = new BB("线程1",500);
BB b2 = new BB("线程2",200);
BB b3 = new BB("线程3",300);
}
}
更多java面试题,java电子书,java视频请参考
www.izixue.com
转载于:https://www.cnblogs.com/Javafirst/archive/2011/02/22/1960359.html