多线程的实现
1.新建一个类,继承于类thread
2.新建一个类实现runnable 接口。不继承thread类,而是直接new thread,但是传递一个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();线程间通信和定时器
线程同步
本文介绍了两种创建多线程的方法:一是通过继承Thread类并重写run方法;二是实现Runnable接口并通过Thread类来启动线程。同时展示了具体的代码示例。
1225

被折叠的 条评论
为什么被折叠?



