第一个例子
package timeprinter;
import java.util.Date;
public class TimePrinter implements Runnable {
int pauseTime;
String name;
public TimePrinter(int x, String n) {
pauseTime = x;
name = n;
}
/**
* @param args
* 当使用 runnable 接口时,您不能直接创建所需类的对象并运行它;必须从 Thread 类的一个实例内部运行它
*
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
// TimePrinter tp1 = new TimePrinter(1000, "Fast Guy"); 继承Thread
// tp1.start();
// TimePrinter tp2 = new TimePrinter(3000, "Slow Guy");
// tp2.start();
Thread t1 = new Thread(new TimePrinter(1000, "Fast Guy"));
t1.start();
Thread t2 = new Thread(new TimePrinter(3000, "Slow Guy"));
t2.start();
}
private void start() {
this.run();
}
@Override
public void run() {
while (true) {
try {
System.out.println(name + ":"
+ new Date(System.currentTimeMillis()));
Thread.sleep(pauseTime);
} catch (Exception e) {
System.out.println(e);
}
}
}
}
程序一直不停的执行,结果如下:
Fast Guy:Thu Aug 19 16:13:55 GMT+08:00 2010
Slow Guy:Thu Aug 19 16:13:55 GMT+08:00 2010
Fast Guy:Thu Aug 19 16:13:56 GMT+08:00 2010
Fast Guy:Thu Aug 19 16:13:57 GMT+08:00 2010
Slow Guy:Thu Aug 19 16:13:58 GMT+08:00 2010
。。。
。。。
第二个例子
//扩展java.lang.Thread类
/**
* File Name: TestMitiThread.java
* Created by: IntelliJ IDEA.2010-7-12
* Copyright: Copyright (c) 2003-2006
* Company: Lavasoft( [url]http://lavasoft.blog.51cto.com/[/url])
* Author: leizhimin
* Modifier: leizhimin
* Date Time: 2007-5-17 10:03:12
* Readme: 通过扩展Thread类实现多线程
*/
public class TestMitiThread {
public static void main(String[] rags) {
System.out.println(Thread.currentThread().getName() + " 线程运行开始!");
new MitiSay("A").start();
new MitiSay("B").start();
System.out.println(Thread.currentThread().getName() + " 线程运行结束!");
}
}
class MitiSay extends Thread {
public MitiSay(String threadName) {
super(threadName);
}
public void run() {
System.out.println(getName() + " 线程运行开始!");
for (int i = 0; i < 10; i++) {
System.out.println(i + " " + getName());
try {
sleep((int) Math.random() * 10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(getName() + " 线程运行结束!");
}
}
main 线程运行开始!
A 线程运行开始!
0 A
main 线程运行结束!
1 A
B 线程运行开始!
0 B
2 A
1 B
3 A
2 B
4 A
3 B
5 A
4 B
6 A
5 B
7 A
6 B
8 A
7 B
9 A
8 B
A 线程运行结束!
9 B
B 线程运行结束!
分享到:
相关推荐
本文给大家介绍java多线程实例,对java多线程知识感兴趣的朋友参考下吧
主要介绍了Java多线程 实例解析,需要的朋友可以参考下
该博客搭配资源 https://blog.csdn.net/weixin_45478419/article/details/129126918 自学多线程时,为了更好理解多线程的实现方式,各个方法,从而编写的。
详细的讲解了java多线程的原理,并配有代码进行实战,适合java初学者和想对多线程有进一步了解的人。
主要介绍了JAVA多线程编程,结合实例形式总结分析了多线程、锁、线程池等相关原理及使用技巧,需要的朋友可以参考下
主要介绍了Java多线程并发执行demo代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
java 多线程例子
java多线程实例
java多线程应用实例,包括wait、notify、notifyAll等的应用方法,经过调试,可以直接运行。