在这种情况下,当用户单击按钮时,会启动一个名为“startAThread”的线程,并且按钮变得不可见。三秒钟后,当线程完成其工作时,按钮再次变为可见。当用户第二次单击该按钮时,它会在 LogCat 中给出错误:
代码:-
public class MainActivity extends Activity {
Handler mHandler;
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button);
mHandler = new Handler(Looper.getMainLooper());
button.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
startAthread.start();
button.setVisibility(View.INVISIBLE);
}
});
}
Thread startAthread = new Thread(new Runnable()
{
@Override
public void run()
{
try
{
Thread.sleep(3000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
mHandler.post(new Runnable()
{
@Override
public void run()
{
button.setVisibility(View.VISIBLE);
}
});
}
});
}
日志猫:-
01-10 19:45:39.861 22473-22473/com.guptamanish712.threadtest W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x418002b8)
01-10 19:45:39.891 22473-22473/com.guptamanish712.threadtest E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.IllegalThreadStateException: Thread already started.
at java.lang.Thread.start(Thread.java:1045)
at com.guptamanish712.threadtest.MainActivity$1.onClick(MainActivity.java:29)
at android.view.View.performClick(View.java:4295)
at android.view.View$PerformClick.run(View.java:17456)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:174)
at android.app.ActivityThread.main(ActivityThread.java:4952)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
at dalvik.system.NativeStart.main(Native Method)