总裁来袭豪门联姻,尖锐湿疣图片,龙腾天朝
第一种:创建一个类继承thread类,重写thread类的run方法,代码如下:
class thread1 extends thread { @override public void run() { while (true) { try { thread.sleep(1000);// 线程睡眠1s } catch (interruptedexception e) { // todo auto-generated catch block e.printstacktrace(); } system.out.println(thread.currentthread().getname());// 打印当前线程名称 } } } public class test { public static void main(string[] args) { thread1 thread1 = new thread1(); thread1.start();//启动线程 } }
第二种方式:创建一个类实现runable接口,重写runable接口的run方法,并将该类的对象作为参数传递给thread类的有参构造方法,代码如下:
class thread2 implements runnable{ @override public void run() { while (true) { try { thread.sleep(1000);// 线程睡眠1s } catch (interruptedexception e) { // todo auto-generated catch block e.printstacktrace(); } system.out.println(thread.currentthread().getname());// 打印当前线程名称 }} } public class test { public static void main(string[] args) { thread thread = new thread(new thread2()); thread.start();//启动线程 } }
两种方式的区别:如果一个类继承thread,则不适合资源共享。但是如果实现了runable接口的话,则很容易的实现资源共享。
实现runnable接口比继承thread类所具有的优势:
1):适合多个相同的程序代码的线程去处理同一个资源
2):可以避免java中的单继承的限制
3):增加程序的健壮性,代码可以被多个线程共享,代码和数据独立
注意:main方法其实也是一个线程。在java中所有的线程都是同时启动的,至于什么时候,哪个先执行,完全看谁先得到cpu的资源。
在java中,每次程序运行至少启动2个线程。一个是main线程,一个是垃圾收集线程。因为每当使用java命令执行一个类的时候,实际上都会启动一个jvm,每一个jvm实际上就是在操作系统中启动了一个进程。
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
浅析我对 String、StringBuilder、StringBuffer 的理解
使用IDEA搭建SSM框架的详细教程(spring + springMVC +MyBatis)
Springboot整合freemarker 404问题解决方案
引入mybatis-plus报 Invalid bound statement错误问题的解决方法
网友评论