public class UsingThread {
/**
* @param args
*/
//创建一个新进程类
/*public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("main thread started");
FactorialThread2 f=new FactorialThread2(10);
f.start();
System.out.println("main thread end");
}
}//usingthread
class FactorialThread2 extends Thread
{
private int num;
public FactorialThread2(int num)
{
this.num=num;
}
public void run()
{
int i=num;
int result=1;
System.out.println("new thread started");
while(i>0)
{result*=i;
i-=1;}
System.out.println("The factorial of"+num+"is"+result);
System.out.println("new thread ends");
}
*/
//创建3个新线程,每个线程睡眠一段时间(0~6秒),然后结束
public static void main(String[] args)
{
System.out.println("Starting thread");
TestTread t1=new TestTread("t1");
TestTread t2=new TestTread("t2");
TestTread t3=new TestTread("t3");
t1.start();
t2.start();
t3.start();
System.out.println("threads starts,main ends/n");
}
}//usingTread
class TestTread extends Thread
{
private int sleepTime;
public TestTread(String name)
{
super(name);
sleepTime=(int)(Math.random()*6000);
}
public void run(){
try {
System.out.println(this.getName()+" going to sleep for "+sleepTime);
Thread.sleep(sleepTime);
} catch (InterruptedException e) {}
// TODO Auto-generated catch block
System.out.println(getName()+" finished");
}
}
/*心得:
1.从Thread类派生一个类,并创建这个类的对象,就可以产生一个新的线程
2.在派生类中需要重写run()方法,
3.调用sleep(long)可以令线程暂停long ms
4.继承Thread的派生类创建对象后,调用它的start()即可以运行一个新线程
*/