JavaSE系列代码32:创建Thread类的子类来创建线程

The content of the method body includes the definition of variables and legal Java statements. Variables declared in the method body and the parameters of the method are called local variables, which are only valid in the method. The parameters of the method are valid in the whole method, and the local variables defined in the method are valid from the position defined by it. Writing a method is exactly like writing a function in C, but it’s called a method here. The name of a local variable must conform to the rules of identifier, following the custom: if Latin letters are used for the name, lowercase letters are used for the initial. If it is composed of more than one word, capitalize the first letter of other words starting from the second word.

class myThread extends Thread   //创建Thread类的子类myThread
{
  private String who;
  public myThread(String str)        //构造方法,用于设置成员变量who
  {
    who=str; 
  }
  public void run()   //覆盖Thread类里的run()方法
  {
    for (int i=0;i<5;i++)
    {
      try
      {
        sleep ((int)(1000*Math.random()));  // sleep()方法必须写在try-catch块内
      }
      catch (InterruptedException e) {}
      System.out.println(who+"正在运行!!");
    }
  }
}
public class Javase_32
{
  public static void main(String[] args)
  {
    myThread f1=new myThread("java1");
    myThread f2=new myThread("java2");
    f1.start();     //注意调用的是start()方法而不是run()方法
    f2.start();     //注意调用的是start()方法而不是run()方法
    System.out.println("主方法main()运行结束!");
  }
}
发布了52 篇原创文章 · 获赞 162 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/blog_programb/article/details/105386387