创建线程的两种方式
2016-07-24 19:27
357 查看
1.继承Thread类,重写run方法
2.实现Runnable接口,重写run方法
package com.thread; //线程 public class Demo1 { public static void main(String[] args) { Cat cat = new Cat(); //启动线程,会导致run函数的运行 cat.start(); } } class Cat extends Thread { // 重写run函数 int times=0; public void run() { while (true) { //休眠一秒,进入阻塞状态 try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } times++; System.out.println("hello world"+times); if(times==10){ //退出 break; } } } }
2.实现Runnable接口,重写run方法
package com.thread; public class Demo2 { public static void main(String[] args) { //启动 Dog dog= new Dog(); Thread t=new Thread(dog); t.start(); } } class Dog implements Runnable { int times = 0; @Override public void run() { while (true) { // 休眠一秒,进入阻塞状态 try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } times++; System.out.println("hello world" + times); if (times == 10) { // 退出 break; } } } }
相关文章推荐
- java对世界各个时区(TimeZone)的通用转换处理方法(转载)
- java-注解annotation
- java-模拟tomcat服务器
- java-用HttpURLConnection发送Http请求.
- java-WEB中的监听器Lisener
- Android IPC进程间通讯机制
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- 介绍一款信息管理系统的开源框架---jeecg
- 聚类算法之kmeans算法java版本
- java实现 PageRank算法
- PropertyChangeListener简单理解
- c++11 + SDL2 + ffmpeg +OpenAL + java = Android播放器
- 插入排序
- 冒泡排序
- 堆排序
- 快速排序
- 二叉查找树