多线程-5

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了多线程-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的主要内容,如果未能解决你的问题,请参考以下文章

5天玩转C#并行和多线程编程

多线程在项目中经常使用的5种场景

python 线程 实现多任务

5-[多线程]-线程理论

java多线程教程

java多线程进阶线程池