首页 > 代码库 > 多线程-5

多线程-5

五、实现线程的第二种方式-实现Runnable接口

1.步骤:
a.自定义类MyRunnable实现Runnable接口。
b.重写run()
c.创建Runnable实现类对象
d.创建Thread线程对象,将Runnable实现类对象作为参数传递

2.构造器:
a.Thread thread = new Tread(IRunnable runnableImpl);
b.Threan thread = new Thread(IRunnabel runnableImpl , String name);

3.因为java是单继承的,所以更加推荐使用实现类的方式来实现多线程。

示例代码:
//a.自定义类MyRunnable实现Runnable接口。
public class MyRunnable implements Runnable {

@Override//b.重写run()
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("线程 : " + Thread.currentThread().getName() + " = " + i);
}
}

}

public class ThreadTEST {
public static void main(String[] args) {
//c.创建Runnable实现类对象
MyRunnable runnable = new MyRunnable();
//d.创建Thread线程对象,将Runnable实现类对象作为参数传递
// Thread thread1 = new Thread(runnable);
// Thread thread2 = new Thread(runnable);
//
// thread1.setName("蛮王");
// thread2.setName("艾希");

Thread thread1 = new Thread(runnable , "盖伦");
Thread thread2 = new Thread(runnable , "卡特");

thread1.start();
thread2.start();
}
}

 

多线程-5