Java - 创建新线程

2022-08-31 17:07:28

我是线程的新手。我想创建一些与主线程分开工作的简单函数。但它似乎不起作用。我只想创建新线程,并在那里做一些独立于主线程上发生的事情的事情。这段代码可能看起来很奇怪,但到目前为止,我对线程没有太多的经验。你能解释一下这有什么问题吗?

  public static void main(String args[]){
      test z=new test();

      z.setBackground(Color.white);

      frame=new JFrame();
      frame.setSize(500,500);
      frame.add(z);
      frame.addKeyListener(z);
      frame.setVisible(true);

      one=new Thread(){
          public void run() {
              one.start();
              try{
                  System.out.println("Does it work?");
                  Thread.sleep(1000);
                  System.out.println("Nope, it doesnt...again.");
              } catch(InterruptedException v){System.out.println(v);}
          }
      };
  }

答案 1

您正在线程的方法中调用该方法。但只有在线程已启动时才会调用该方法。请改为执行以下操作:one.start()runrun

one = new Thread() {
    public void run() {
        try {
            System.out.println("Does it work?");

            Thread.sleep(1000);

            System.out.println("Nope, it doesnt...again.");
        } catch(InterruptedException v) {
            System.out.println(v);
        }
    }  
};

one.start();

答案 2

你可以这样做:

    Thread t1 = new Thread(new Runnable() {
    public void run()
    {
         // code goes here.
    }});  
    t1.start();