当前页面: 开发资料首页 → Java 专题 → 菜鸟初学Java的备忘录(三)
摘要: 菜鸟初学Java的备忘录(三)
class testthread{
public static void main(String args[]){
Thread t=Thread.currentThread();
t.setName("This Thread is running");
System.out.println("The running thead:"+t);
try{
for(int i=0;i<5;i++)
{
System.out.println("Sleep time"+i);
Thread.sleep(1000);//挂起线程,就是让线程休息一会儿,不占用系统资源,因此其它线程可以继续.这里的Thread缺省表示主线程
}
}catch(InterruptedException e){System.out.println("thread has wrong");}
}
}
public class TwoThread{
public static void main(String args【】){
new SimpleThread("HelloWorld1").start();//创建两个线程的实例,就这么简单
new SimpleThread("HelloWorld2").start();
}
}
class SimpleThread extends Thread{ file://真正的内容在这里
public SimpleThread(String str){
super(str);//super代表SimpleThread类的直接父类,这里就是Thread
}
file://我们要线程做的事情都在这里了
public void run(){
for(int i=0;i<10;i++){
System.out.println(i+" "+getName());
try{
sleep((int)(Math.random()*1000));
}catch(InterruptedException e){}
}
System.out.println("Done!"+getName());
}
}
class TwoThread implements Runnable{
TwoThread(){
Thread t1=Thread.currentThread();
t1.setName("The first main thread");
System.out.println("The running thead:"+t1);
Thread t2=new Thread(this,"the second thread");//注意这里的this,它表明新线程即t2将会做的事情由this对象来决定,也就是由twothread的run函数来决定
System.out.println("create another thread");
t2.start();//调用该函数将使线程从run函数开始执行
try{
System.out.println("first thread will sleep");
Thread.sleep(3000);
}catch(InterruptedException e){System.out.println("first thread has wrong");}
System.out.println("first thread exit");
} public void run()//定义run()函数,在本程序中也就是t2这个新的线程会做的事情
{
try{
for(int i=0;i<5;i++)
{
System.out.println("sleep time for thread 2:"+i);
Thread.sleep(1000);
}
}catch(InterruptedException e){System.out.println("thread has wrong");}
System.out.println("second thread exit");
}
public static void main(String args【】){
new TwoThread();//触发构造函数
}
}
The running rhread:Thread[The first main thread,5,main]
creat another thread
first thread will sleep
Sleep time for thread 2:0
Sleep time for thread 2:1
Sleep time for thread 2:2
first thread exit
Sleep time for thread 2:3
Sleep time for thread 2:4
second thread exit