Android 多线程编程

Android 多线程编程

 1 //1.多线程
 2     进程:操作系统的多道程序
 3     线程:同一个程序的多条路径
 4 
 5 //2.创建多线程程序
 6    创建一个类extends Thread
 7    重写run方法
 8    在main方法中创建对象
 9    对象.start() 开启线程
10      
11 //3.多线程的特殊语法
12     在main方法中直接开启多线程
13     方法1
14     new Thread(){
15             public void run() {
16                 for(int i=0;i<100;i++){
17                     System.out.println("运行了"+i);
18                 }
19                 
20             };
21             
22     }.start();
23 
24     方法2
25     在属性上创建多线程对象
26     private static Thread t1 = new Thread(){  //属性
27         public void run() {
28             for(int i=0;i<100;i++){
29                 System.out.println("线程t1");
30             }
31         };
32     } ;
33         
34 //4.线程的睡眠
35     Thread.sleep(毫秒)
36         
37 //5.实现runnable接口处理多线程
38     写一个类实现Runnable,并重写run方法
39     在main方法中创建Thread对象开启多线程
40 
41     匿名内部类的写法
42     new Thread(new Runnable() {
43             public void run() {
44                 for(int i=0;i<10;i++){
45                     System.out.println("====");
46                     try {
47                         Thread.sleep(500);
48                     } catch (Exception e) {
49                         
50                     }
51                 }
52             }
53     }).start();
54 
55 //6.Service组件
56     Activity  Ui界面
57     Intent
58     Service没有界面 后台的操作
59     
60     创建一个类extends Service
61     重写Service 的 oncreate方法
62                    ondestory方法
63     注册Service
64      <service android:name="com.example.andservice01.MyService"></service>
65     
66     点击按钮 通过Intent启动service
67     //启动service
68                 Intent intent = new Intent();
69                 intent.setClass(MainActivity.this, MyService.class);
70                 startService(intent);
71                 
72     停止Service
73     //销毁service
74                 Intent intent2 = new Intent();
75                 intent2.setClass(MainActivity.this, MyService.class);
76                 stopService(intent2);
77                 break;










原文地址:https://www.cnblogs.com/hbtmwangjin/p/7883839.html