Java-创建一个新线程 [英] Java - creating a new thread

查看:556
本文介绍了Java-创建一个新线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是线程新手.我想创建一些与主线程分开工作的简单函数.但这似乎不起作用.我只想创建一个新线程,并在那里独立于主线程上发生的事情做一些事情.这段代码看起来很怪异,但是到目前为止,我对线程的了解还很少.你能解释一下这是怎么回事吗?

I'm new to threads. I wanted to create some simple function working separately from main thread. But it doesn't seem to work. I'd just like to create new thread and do some stuff there independently of what's happening on main thread. This code may look weird but I don't have much experience with threading so far. Could you explain me what's wrong with this?

  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);}
          }
      };
  }

推荐答案

您正在线程的run方法中调用one.start()方法.但是run方法仅在线程已经启动时才被调用.改为执行此操作:

You are calling the one.start() method in the run method of your Thread. But the run method will only be called when a thread is already started. Do this instead:

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();

这篇关于Java-创建一个新线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆