android中的主线程不需要新建。
Thread.sleep设置程序阻塞。
1 public class MainActivity extends AppCompatActivity { 2 3 @Override 4 protected void onCreate(Bundle savedInstanceState) { 5 super.onCreate(savedInstanceState); 6 setContentView(R.layout.activity_main); 7 findViewById(R.id.bt).setOnClickListener(new View.OnClickListener() { 8 @Override 9 public void onClick(View v) { 10 try { 11 Thread.sleep(1000); 12 System.out.print("The thread is running, is sleeping"); 13 } catch (InterruptedException e) { 14 e.printStackTrace(); 15 } 16 } 17 }); 18 } 19 }
新建子线程后,按下Button,不会卡死,会立即弹起。
1 new Thread(){ 2 @Override 3 public void run() { 4 try { 5 while (true){ 6 sleep(1000); 7 System.out.print("Hello, this is the new thread!"); 8 } 9 } catch (InterruptedException e) { 10 e.printStackTrace(); 11 } 12 } 13 }.start();
时间: 2024-10-10 07:44:46