java基础之多线程二:多线程实现方式
2024-09-04 15:38:24
方式一: 继承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);
}
}
}
最新文章
- Android可移动控件
- PHP程序员如何突破成长瓶颈(php开发三到四年)
- tortoiseSVN svn+ssh
- HDU 4292 Food
- Validform使用
- 正则表达式(RegExp)
- Windows Server 2003单网卡搭建VPN
- 在自定义的dwt文件中调用page_header.lbi和page_footer.lbi
- CANVAS运用-对图片的压缩上传(仅针对移动浏览器)
- linux下mysql的表名问题
- [Angular 2] ng-model and ng-for with Select and Option elements
- php中的require-once
- Linux rpm 命令参数使用详解[介绍和应用](转)
- ggplot2 scale相关设置-坐标转换
- JAVA入门[2]-安装Maven
- Redis 集群环境添加节点失败问题
- Selenium+Java的TestNG测试报告优化
- Oracle 客户端 NLS_LANG 的设置
- JQuery请求数据的方式
- (转)【风宇冲】Unity3D教程宝典之Blur
热门文章
- 在Linux上部署DotNet Core项目的时候发现Apache无法转发Kestrel的5000端口的问题
- volatile与const综合分析
- Android sharedUserId 使用
- Bellman-Ford算法——解决负权边
- 《DSP using MATLAB》示例Example7.23
- 如何理解Robot Framework
- 【spring源码学习】spring的IOC容器之自定义xml配置标签扩展namspaceHandler向IOC容器中注册bean
- raw_in_fields
- (转)Eclipse 扩大内存
- ubuntu下使用code::blocks编译运行一个简单的gtk+2.0项目