java线程之使用Runnable接口创建线程的方法
更新时间:2013年05月02日 16:23:26 作者:
本篇文章介绍了,java中使用Runnable接口创建线程的方法。需要的朋友参考下
实现Runnable接口的类必须使用Thread类的实例才能创建线程。通过Runnable接口创建线程分为两步:
1. 将实现Runnable接口的类实例化。
2. 建立一个Thread对象,并将第一步实例化后的对象作为参数传入Thread类的构造方法。
最后通过Thread类的start方法建立线程。
下面的代码演示了如何使用Runnable接口来创建线程:
复制代码 代码如下:
package mythread;
public class MyRunnable implements Runnable
{
public void run()
{
System.out.println(Thread.currentThread().getName());
}
public static void main(String[] args)
{
MyRunnable t1 = new MyRunnable();
MyRunnable t2 = new MyRunnable();
Thread thread1 = new Thread(t1, "MyThread1");
Thread thread2 = new Thread(t2);
thread2.setName("MyThread2");
thread1.start();
thread2.start();
}
}
上面代码的运行结果如下:
复制代码 代码如下:
MyThread1
MyThread2
相关文章
Monaco Editor实现sql和java代码提示实现示例
这篇文章主要为大家介绍了Monaco Editor代码提示sql和java实现示例,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2022-08-08
Java中的runnable 和 callable 区别解析
Runnable接口用于定义不需要返回结果的任务,而Callable接口可以返回结果并抛出异常,通常与Future结合使用,Runnable适用于简单的后台任务和定时任务,而Callable适用于并行计算、异步操作和复杂任务,选择使用哪个接口取决于具体的应用场景,感兴趣的朋友一起看看吧2025-03-03
Java中的SpringAOP、代理模式、常用AspectJ注解详解
这篇文章主要介绍了Java中的SpringAOP、代理模式、常用AspectJ注解详解,Spring提供了面向切面编程的丰富支持,允许通过分离应用的业务逻辑与系统级服务,例如审计和事务管理进行内聚性的开发,需要的朋友可以参考下2023-09-09


最新评论