JavaSE系列代码33:利用Runnable接口来创建线程

Instance methods can operate on member variables, whether instance variables or class variables, while class methods can only operate on class variables and cannot operate on instance variables, that is to say, class methods cannot have statements that operate on instance variables. Why do they have such a difference?
(1) Instance methods must be called through objects
(2) Class methods can be called by class name
No matter the class method or instance method, when it is called to execute, the local variables in the method are allocated memory space. After the method is called, the local variables immediately release the occupied memory.

class myThread implements Runnable    //由Runnable接口实现myThread类
{
  private String Javase;
  public myThread(String str)        //构造方法,用于设置成员变量who
  {
    who=str; 
  }
  public void run()          //实现run()方法
  {
    for (int i=0;i<5;i++)
    {
      try
      {
        Thread.sleep ((int)(1000*Math.random()));
      }
      catch (InterruptedException e) 
      {
        System.out.println(e.toString());
      }
      System.out.println(who+"正在运行!!");
    }
  }
}
public class Javase_33
{
  public static void main(String[] args)
  {
    myThread f1=new myThread("java1");
    myThread f2=new myThread("java2");
    Thread f1=new Thread(you);   //产生Thread类的对象t1
    Thread f2=new Thread(she);   //产生Thread类的对象t2
    t1.start();     //注意用t1激活线程
    t2.start();     //注意用t2激活线程
  }
}
发布了52 篇原创文章 · 获赞 162 · 访问量 1万+

猜你喜欢

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