多线程:创建Thread为什么要调用start启动,而不能直接调用run方法
来源:互联网 发布:matlab读取excel数据 编辑:程序博客网 时间:2024/06/06 10:05
最近在学习Android Service时遇到这样多线程问题。
start()方法启动线程后,整个线程处于就绪状态,等待虚拟机调度, 然后通过此Thread类调用方法run()来完成其运行操作的, 这里方法run()称为线程体,它包含了要执行的这个线程的内容, Run方法运行结束, 此线程终止。期间虚拟机是分时间片轮番调用各个线程体的。
run()方法启动是当作普通方法的方式调用,这里虚拟机不会线程调度,虚拟机会执行这个方法直到结束后自动退出。
参考进程、线程调度,javaThread生命周期。
package com.example.wangchuncheng.myservice;import android.app.Service;import android.content.Intent;import android.os.IBinder;public class MyService extends Service { private boolean running = false; private String data = "这是默认信息"; public MyService() { } @Override public IBinder onBind(Intent intent) { // TODO: Return the communication channel to the service. throw new UnsupportedOperationException("Not yet implemented"); } @Override public int onStartCommand(Intent intent, int flags, int startId) { data = intent.getStringExtra("data"); return super.onStartCommand(intent, flags, startId); } @Override public void onCreate() { super.onCreate(); running = true; new Thread(){ @Override public void run() { super.run(); while(running){ System.out.println(data); try { sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }.start(); //这里使用run的话,开始服务后会卡死,导致程序无响应 } @Override public void onDestroy() { super.onDestroy(); running = false; }}
阅读全文
0 0
- 多线程:创建Thread为什么要调用start启动,而不能直接调用run方法
- 为什么我们调用start()方法时会执行run()方法,为什么我们不能直接调用run()方法?
- 调用线程对象的start()方法会执行run(),为什么不能直接调用run()方法??
- Thread直接调用run()和start()方法的区别
- 多线程为什么调用start而不是调用run方法
- 为什么我们调用start()方法时会执行run()方法?为什么我们不能直接调用run()方法?他们之间有什么区别?
- 线程为什么调用start()而不是直接调用run()
- 创建线程的几种方式,以及为什么启动线程不用run,而用start方法!!!
- 创建线程的几种方式,以及为什么启动线程不用run,而用start方法。
- Thread调用start、run区别
- 多线程执行时为什么调用的是start()方法而不是run()方法
- Thread中调用start()和run()方法的区别
- Thread调用run()和start()方法的区别
- 调用run()方法启动线程和start()方法启动线程
- Java直接调用Thread类中的run()方法
- Thread类调用run()方法和调用start()方法的区别
- 调用C# Thread.Start()方法
- Android Thread类中方法run()与start()调用时,实际的线程运行情况!
- 理财学习与思考
- Python数组统计排序问题
- 中国联通大数据应用
- (M)Dynamic Programming:377. Combination Sum IV
- 复习一下指针
- 多线程:创建Thread为什么要调用start启动,而不能直接调用run方法
- python json和java json的使用
- C++ 数组
- 10月 5日 c语言 一维数组 处理Fibonacci 数列问题
- 128. Longest Consecutive Sequence(最长连续序列)
- 17、C#中的常量和结构的定义与使用
- 数据库——彻底明白超键、候选键、主键、外键
- POI导入Excel的公共方法
- android中src和background区别