java学习笔记-Thread
2013-09-05 19:29
405 查看
java定义了创建线程的两种方法
1.实现Runnable接口
2.扩展Thread类本身
1.实现Runnable接口:
可以依托任何Runnable接口的对象来创建线程。但是为了实现Runnable接口,类需要实现run()方法。
创建了实现Runnable接口的类之后,可以在类中实例化Thread类型的对象。Thread类定义了几个构造函数,下面实例中使用的构造函数如下:
Thread(Runnable threadOb,String threadName) //该构造函数中,threadOb是实现了Runnable接口的类的实例或对象;
实例:
实现Runnable接口的类NewThread代码:
测试类ThreadDemo代码:
运行结果如下图:
ps:Thread.currentThread()方法输出的是当前线程线程名称,优先级5,线程所处的线程组main。
未完待续...
1.实现Runnable接口
2.扩展Thread类本身
1.实现Runnable接口:
可以依托任何Runnable接口的对象来创建线程。但是为了实现Runnable接口,类需要实现run()方法。
创建了实现Runnable接口的类之后,可以在类中实例化Thread类型的对象。Thread类定义了几个构造函数,下面实例中使用的构造函数如下:
Thread(Runnable threadOb,String threadName) //该构造函数中,threadOb是实现了Runnable接口的类的实例或对象;
实例:
实现Runnable接口的类NewThread代码:
public class NewThread implements Runnable{ Thread t; public NewThread() { //this是实现Runnable接口的类的实例 t=new Thread(this,"Demo Thread"); System.out.println("Child thread:"+t); t.start(); } public void run() { try { for(int i=5;i>0;i--) System.out.println("Child thread:"+i+":"+Thread.currentThread()); Thread.sleep(500); } catch (InterruptedException e) { System.out.println("Child Interrupted."); } System.out.println("Exiting Child thread."); } }
测试类ThreadDemo代码:
public class ThreadDemo { public static void main(String[] args) { // TODO Auto-generated method stub new NewThread(); try{ for(int i=5;i>0;i--){ System.out.println("Main Thread:"+i+":"+Thread.currentThread()); Thread.sleep(1000); } }catch (InterruptedException e) { System.out.println("Main thread Interrupted."); } System.out.println("Exiting Main thread."); } }
运行结果如下图:
ps:Thread.currentThread()方法输出的是当前线程线程名称,优先级5,线程所处的线程组main。
未完待续...
相关文章推荐
- javaThread技术--学习笔记
- java学习笔记--Thread
- 学习java多线程的笔记1--Thread(Runnable t)与重写run()方法等
- java学习笔记-Thread
- Java学习笔记67. 创建多线程的方法 -- 通过继承thread类创建多线程
- JAVA学习笔记(三十七)- 创建继承Thread的线程
- Java 学习笔记 (5) - 线程 Thread
- Java 螺纹第三版 第一章Thread介绍、 第二章Thread创建和管理学习笔记
- java.lang.Thread学习笔记
- 大数据课程体系-学习笔记-第一阶段-Java Thread
- Android(java)学习笔记2:继承Thread类创建线程类
- 【Java基础学习笔记】Thread+JLabel实现线程
- 学习笔记4:java中Thread类的方法小结
- Java学习笔记44(多线程一:Thread类)
- JAVA 学习笔记 - 【Thread简单概念】
- 学习笔记2:java中Thread类与线程的创建
- Java并发学习笔记(13)线程之间的协作(Object.wait(),notifu(),notifyAll() Thread.join())
- Thinking in Java学习笔记 Thread.UncaughtExceptionHandler接口实现捕获线程内异常
- java学习笔记-java.lang.Thread
- java.lang.ThreadGroup学习笔记