线程未运行

时间:2012-04-29 05:21:08

标签: java multithreading

我有一个实现runnable的java程序。在正文中,我有Thread animator = new Thread();然后animator.start();问题是我的程序的run()方法没有执行。 我错过了什么

2 个答案:

答案 0 :(得分:2)

正如你所说的实现runnable的java程序。

在那个班级(名字叫Animator)身上你写了

Thread animator = new Thread();
animator.start();

如果我没错?

传递runnable类实例,这里我认为在创建线程

时它将是this
Thread animator = new Thread(this);
animator.start();

答案 1 :(得分:1)

你可以这样试试

public class BackgroundActivity {

/**
 * Attempts to execute the user activity.
 * 
 * @return The thread on which the operations are executed.
 */
public Thread doWork() {
    final Runnable runnable = new Runnable() {
        public void run() {
            System.out.println("Background Task here");
        }
    };

    // run on background thread.
    return performOnBackgroundThread(runnable);
}

/**
 * Executes your requests on a separate thread.
 * 
 * @param runnable
 *            The runnable instance containing mOperations to be executed.
 */
private Thread performOnBackgroundThread(final Runnable runnable) {
    final Thread t = new Thread() {
        @Override
        public void run() {
            try {
                runnable.run();
            } finally {
            }
        }
    };
    t.start();
    return t;
}

}

最后来自main方法的doWork()方法

 /**
 * @param args
 */
public static void main(String[] args) {
    BackgroundActivity ba = new BackgroundActivity();
    Thread thread = ba.doWork();

    //You  can manages thread here
}

希望,它会帮助你。