【Java基础】JAVA 使用线程的几种方式
2024-09-05 14:50:47
之前放在自己网站上的例子,因为网站关闭,已经找不到了,想用的时候,没有的话又重新翻书是很麻烦的事情。所以重新记录一下,以备将来查看。
第一种,让任务类继承Runable接口,然后将任务类对象放入Thread对象的构造器,通过Thread.start()方法执行调用。
package com.test.thread; public class ThreadTest1 {
public static void main(String[] args) {
Thread thread = new Thread(new task(1));
thread.start();
System.out.println("hello");
}
} class task implements Runnable { private final int taskid; public task(int taskid) {
this.taskid = taskid;
} public void run() {
System.out.println(this);
} @Override
public String toString() {
return "task [taskid=" + taskid + "]";
} }
执行结果:
hello
task [taskid=1]
第二种,就是第一种方式的改进,好处之一就是不用显示地创建Thread对象了,其他的好处还有,我不知道。这是JAVA SE5/6启动任务的优选方法。和方式一的区别,仅仅是main方法的区别:
ExecutorService exec = Executors.newCachedThreadPool();
exec.execute(new Task1(1));
还有一种就是继承Thread类啦。并发编程太复杂了, 暂时写这么多把,以后用到的时候再说。
最新文章
- JDBC关于时间的存取
- iOS,视图相关
- div基础
- ZPL打印中文信息
- A + B Problem II
- [Effective JavaScript 笔记]第20条:使用call方法自定义接收者来调用方法
- stuts-security.xml
- (转)IOS中获取各种文件的目录路径的方法
- [RxJS] Error handling operator: catch
- 内存泄露 Memory Leaks
- js-轮播图
- BCB实现BMP图片的RGB分解(转)
- coreCLR系列随笔 之ClrJit项目之alloc.cpp文件分析(1)
- java设计模式--单列模式
- python 之 初识模块
- 你有可能不知道的css浮动问题
- [OC] 使用 cocoaPods 导入 AFNetworking
- pytorch-1.0 踩坑记录
- jenkins构建触发器详解-不登录触发远程构建
- Save vtkMatrix4x4 to a file 保存到文件