android 线程 和 定时器

本文介绍了两种创建多线程的方法:一是通过继承Thread类并重写run方法;二是实现Runnable接口并通过Thread类来启动线程。同时展示了具体的代码示例。
多线程的实现
1.新建一个类,继承于类thread
    class MyThread extends Thread {  
        //继承Thread类,并改写其run方法  
        private final static String TAG = "MyThread";  

        public void run(){  
            Log.d(TAG, "run");  
            for(int i = 0; i<100; i++)  
            {  
                Log.e(TAG, Thread.currentThread().getName() + "i =  " + i);  
            }  
        }  
        
    }  
    
调用
				//new MyThread().start();  
				MyThread th = new MyThread();
				th.start();


2.新建一个类实现runnable 接口。不继承thread类,而是直接new thread,但是传递一个runnable接口给thread.
    class MyRunnable implements Runnable{  
        private final static String TAG = "MyRunnable";  
          
        @Override  
        public void run() {  
            // TODO Auto-generated method stub  
            Log.d(TAG, "run");  
            for(int i = 0; i<1000; i++)  
            {  
                Log.e(TAG, Thread.currentThread().getName() + "i =  " + i);  
            }  
        }  
    }  
调用
				// new Thread(new MyRunnable()).start();  
				 MyRunnable myrun=new MyRunnable();
				 Thread th =new Thread(myrun);
				 th.start();

或者定义调用一块的,
					new Thread( new Runnable(){
				        private final static String TAG = "MyRunnable";  
				        @Override  
				        public void run() {  
				            // TODO Auto-generated method stub  
				            Log.d(TAG, "run");  
				            for(int i = 0; i<1000; i++)  
				            {  
				                Log.e(TAG, Thread.currentThread().getName() + "i =  " + i);  
				            }  
				        }  
					}).start();

线程间通信和定时器




线程同步
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值