多线程的一个例子
2005-12-26 23:43
489 查看
这个程序是照抄书上的例子,,《Java项目培训指南》,感觉还是很有收获,,,
import java.lang.Thread;
import java.lang.System;
import java.lang.Math;
import java.lang.InterruptedException;
public class Thread1
{
public static void main(String args[])
throws java.io.IOException
{
System.out.println("if want to show the result,press Return ");
MyThread thread1=new MyThread("thread1");
MyThread thread2=new MyThread("thread2");
thread1.start();
thread2.start();
char ch;
while ((ch=(char)System.in.read())!='/n');
thread1.tStart();
thread2.tStart();
while (thread1.isAlive()||thread2.isAlive())
{
}
System.out.println("The thread test is end.");
}
}
class MyThread extends Thread
{
private boolean keepRunning=true;
public MyThread(String id)
{
super(id);
}
void randomWait()
{
try
{
sleep((long)(3000*Math.random()));
}
catch(InterruptedException x)
{
System.out.println("Interrpted!!");
}
}
public void tStart()
{
keepRunning=false;
}
public void run()
{
int i=0;
while (keepRunning) i++;
for (int j=0;j<3;j++)
{
randomWait();
System.out.println("I am "+getName()+" - - I hava run "+i+" times.");
i++;
}
System.out.println(getName()+" is dead!");
}
}
import java.lang.Thread;
import java.lang.System;
import java.lang.Math;
import java.lang.InterruptedException;
public class Thread1
{
public static void main(String args[])
throws java.io.IOException
{
System.out.println("if want to show the result,press Return ");
MyThread thread1=new MyThread("thread1");
MyThread thread2=new MyThread("thread2");
thread1.start();
thread2.start();
char ch;
while ((ch=(char)System.in.read())!='/n');
thread1.tStart();
thread2.tStart();
while (thread1.isAlive()||thread2.isAlive())
{
}
System.out.println("The thread test is end.");
}
}
class MyThread extends Thread
{
private boolean keepRunning=true;
public MyThread(String id)
{
super(id);
}
void randomWait()
{
try
{
sleep((long)(3000*Math.random()));
}
catch(InterruptedException x)
{
System.out.println("Interrpted!!");
}
}
public void tStart()
{
keepRunning=false;
}
public void run()
{
int i=0;
while (keepRunning) i++;
for (int j=0;j<3;j++)
{
randomWait();
System.out.println("I am "+getName()+" - - I hava run "+i+" times.");
i++;
}
System.out.println(getName()+" is dead!");
}
}
相关文章推荐
- Java一个多线程的经典例子
- 关于多线程的一个例子(UI实时显示)
- java学习--多线程发生死锁的一个例子
- [转]一个简单的Linux多线程例子 带你洞悉互斥量 信号量 条件变量编程
- 利用Semaphore实现多线程的一个例子
- 一个关于多线程的简单例子(两种实现方法)
- 本文一个例子展开,介绍Linux下面线程的操作、多线程的同步和互斥
- 多线程的一个例子
- php pthreads 多线程扩展的使用:一个较为稳定例子。
- 一个多线程的经典例子
- 一个多线程的小例子---C#高级编程学习
- 一个多线程使用方法例子
- ABC线程如何保证顺序执行 关于多线程的一个小例子
- Live555 的一个缺陷--例子不能支持多线程(已经修改成支持多线程)
- 一个多线程的死锁和锁争用的例子
- Java 多线程编程之五:一个理解 wait() 与 notify() 的例子
- 一个学习java多线程的好例子
- 一个验证HashMap在多线程环境下线程不安全的例子及dump分析
- 多线程的一个小例子
- QThread使用的一个例子----多线程