JavaSE+Thread
来源:互联网 发布:sql replace 替换空格 编辑:程序博客网 时间:2024/06/06 20:42
publicclass CurrentThread {
publicstaticvoid print(){
for (int i=0;i<100;i++){
System.out.print(i+";");
try {
System.out.print(Thread.currentThread().getName());
Thread.sleep(2000);
System.out.println();
} catch (NumberFormatException e) {
//TODOAuto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
//TODOAuto-generated catch block
e.printStackTrace();
}
System.out.print(i+3+"+");
}
}
//
publicstaticvoid main(String[] args) {
// TODOAuto-generated method stub
new Thread() {
publicvoid run() {
//Thread-0
CurrentThread.print();
}
}.start();
//main Thread
// CurrentThread.print();
}
}
1.做1个延迟的功能,这里用Thread.sleep()做测试,原本以为Thread.sleep()只是能用到线程里,但我将主方法里的线程注释掉,直接使用CurrentThread.print();还是会延迟2秒打印,当时的2点疑问在此分享解答:
1.当主方法的线程不注释掉,调用CurrentThread.print();时,Thread.sleep()里的线程是指哪个线程?
2.当主方法的线程注释掉,调用CurrentThread.print();时,为何还会跟没注释掉1样?
1.System.out.print(Thread.currentThread().getName());会告诉你原因:
1.new Thread()里的执行的是新new出来的Thread-0;
2.主方法里直接运行的是main线程执行的;
1.Object.wait()做延时处理源码展示:
publicclass WaitimplementsRunnable{
private Objectobject =new Object();
@Override
publicvoid run() {
// TODOAuto-generated method stub
try {
synchronized (object) {
for (int i = 0; i < 100; i++) {
System.out.print(i+"+");
object.wait(2*1000);
System.out.print(i + 3+";");
object.notifyAll();
System.out.println();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
return;
}
}
//
publicstaticvoid main(String args[]) {
ExecutorService executorService =Executors.newFixedThreadPool(1);
Wait wait = new Wait();
executorService.execute(wait);
executorService.shutdown();
while (!executorService.isTerminated()) {
}
}
}
- JavaSE+Thread
- JavaSE之线程Thread
- Javase—Thread多线程
- JavaSE第九十九讲:Thread类源码深度剖析
- javaSE
- javaSE
- javaSE
- JavaSE
- javase
- javase
- javaSE
- JAVASE
- JavaSE
- Javase
- javase
- javase
- JavaSE
- JAVASE
- HDU 4521(dp)
- Python 与 C++ 混合编程 实验
- hadoop 完全分布式 下 datanode无法启动解决方法
- python中的含有 *args 和**kwargs的用法 作为参数的函数,参数输入问题
- Linux如何通过PAM限制用户登录失败次数
- JavaSE+Thread
- git 命令
- Offline Image Viewer Guide
- AndroidL 传感器系统
- quartz.net
- SSL/TLS协议运行机制的概述
- 理论知识
- C++文件读写详解(ofstream,ifstream,fstream)
- php---ajax传递多维数组到后台