方式一: 继承Thread类.
/*
* main函数也叫主函数(也叫主线程),
* 因为所有代码的执行都是从这里开始的.
*/
public static void main(String[] args) {
// 在测试类中,创建线程对象.
MyThread mt1 = new MyThread(); // 开启线程. //start()
//mt1.run(); //如果调用run()方法, 只是普通的方法调用.
mt1.start(); //开启线程必须调用start()方法, 该方法会自动去调用run()方法.
//mt1.start(); //同一线程不能重复开启, 否则会报: IllegalThreadStateException异常. for (int i = 1; i <= 100; i++) {
System.out.println("main...." + i);
}
} /**
* 自定义的线程类: MyThread
* @author
*
*/
// 1) 定义一个类(MyThread), 继承Thread类.
public class MyThread extends Thread{
//2) 重写Thread#run(). @Override
public void run() {
//3) 把要执行的代码放入run()方法中.
for (int i = 1; i <= 100; i++) {
System.out.println("run______________" + i);
}
}
}
方式二: 实现Runnable接口.
public static void main(String[] args) {
//格式化代码: alt + shift + s --> 字母f // 在测试类中, 创建Runnable接口的子类对象,
MyRunnable mr = new MyRunnable();
// 并将其作为参数传入Thread类的构造, 创建线程对象.
Thread th = new Thread(mr); // 开启线程. //start()
th.start(); for (int i = 1; i <= 100; i++) {
System.out.println("main***" + i);
} } /**
* Runnable接口的具体实现类
* @author
*
*/
//1) 定义一个类(MyRunnable), 实现Runnable接口.
public class MyRunnable implements Runnable {
//2) 重写Runnable#run().
@Override
public void run() {
//3) 把要执行的代码放入run()方法中.
for (int i = 1; i <= 100; i++) {
System.out.println("run______________" + i);
}
}
}
												

最新文章

  1. Android可移动控件
  2. PHP程序员如何突破成长瓶颈(php开发三到四年)
  3. tortoiseSVN svn+ssh
  4. HDU 4292 Food
  5. Validform使用
  6. 正则表达式(RegExp)
  7. Windows Server 2003单网卡搭建VPN
  8. 在自定义的dwt文件中调用page_header.lbi和page_footer.lbi
  9. CANVAS运用-对图片的压缩上传(仅针对移动浏览器)
  10. linux下mysql的表名问题
  11. [Angular 2] ng-model and ng-for with Select and Option elements
  12. php中的require-once
  13. Linux rpm 命令参数使用详解[介绍和应用](转)
  14. ggplot2 scale相关设置-坐标转换
  15. JAVA入门[2]-安装Maven
  16. Redis 集群环境添加节点失败问题
  17. Selenium+Java的TestNG测试报告优化
  18. Oracle 客户端 NLS_LANG 的设置
  19. JQuery请求数据的方式
  20. (转)【风宇冲】Unity3D教程宝典之Blur

热门文章

  1. 在Linux上部署DotNet Core项目的时候发现Apache无法转发Kestrel的5000端口的问题
  2. volatile与const综合分析
  3. Android sharedUserId 使用
  4. Bellman-Ford算法——解决负权边
  5. 《DSP using MATLAB》示例Example7.23
  6. 如何理解Robot Framework
  7. 【spring源码学习】spring的IOC容器之自定义xml配置标签扩展namspaceHandler向IOC容器中注册bean
  8. raw_in_fields
  9. (转)Eclipse 扩大内存
  10. ubuntu下使用code::blocks编译运行一个简单的gtk+2.0项目