请完成下列Java程序:程序的功能演示了如何通过实现Runnable接口创建线程对象,程序中定义了一个类B,类中重写了含一个字符串参数的构造方法,并实现了Runnable接口,即在类B中编写了接口中的run()方法的方法体。还定义了一个应用程序类ex35_2,其中创建类B的3个对象b1,b2和b3作为线程对象t1,t2和t3的参数,并启动这3个线程。 注意:请勿改动main()主方法和其他已有语句内容,仅在下划线处填入适当的语句。 程序运行结果如下:
public class ex35_2 { public static void main(String args[ ]) { Runnable b1=new B("First"); Runnable b2=new B("Second"); Runnable b3=new B("Third"); Thread t1=new Thread(b1); Thread t2=new Thread(b2); Thread t3=new Thread(b3); t1.start (); t2.start (); t3.start(); } }class B _____________________ Runnable { String s; public B(String str) { s=str; } _________________ { for(int i=1;i<3;i++) {System. out. println ( s+ "运行!"); try { Thread.sleep((int) (Math.random() *100) ); }catch (InterruptedException e) {e.printStackTrace ( ); } } System. out.println (s+"结束!"); } }
参考答案:
解析:implements public void run() 本题主要考查Java中有关线程的基本操作。解题关键是要熟练掌握有关线程的基本知识。在Java中创建线程有两种基本方法:(1)是通过实现Runnable接口创建线程。(2)通过继承Thread类创建线程。第1个空,应该填implements关键字,其功能是实现Runnable接口。第2个空,应该填public void run(),其功能是重写run()方法。