java多线程进修劈头
import java.io.*;
//多线程编程
public class MultiThread
{
public static void main(String args[])
{
System.out.println("我是主线程!");
//下面建设线程实例thread1
ThreadUseExtends thread1=new ThreadUseExtends();
//建设thread2时以实现了Runnable接口的THhreadUseRunnable类实例为参数
Thread thread2=new Thread(new ThreadUseRunnable(),"SecondThread");
thread1.start();//启动线程thread1使之处于停当状态
//thread1.setPriority(6);//配置thread1的优先级为6
//优先级将抉择cpu空出时,处于停当状态的线程谁先占领cpu开始运行
//优先级范畴1到10,MIN_PRIORITY,MAX_PRIORITY,NORM_PAIORITY
//新线程担任建设她的父线程优先级,父线程凡是有普通优先级即5NORM_PRIORITY
System.out.println("主线程将挂起7秒!");
try
{
Thread.sleep(7000);//主线程挂起7秒
}
catch (InterruptedException e)
{
return;
}
System.out.println("又回到了主线程!");
if(thread1.isAlive())
{
thread1.stop();//假如thread1还存在则杀掉他
System.out.println("thread1休眠过长,主线程杀掉了thread1!");
}
else
System.out.println("主线程没发明thread1,thread1已醒顺序执行竣事了!");
thread2.start();//启动thread2
System.out.println("主线程又将挂起7秒!");
try
{
Thread.sleep(7000);//主线程挂起7秒
}
catch (InterruptedException e)
{
return;
}
System.out.println("又回到了主线程!");
if(thread2.isAlive())
{
thread2.stop();//假如thread2还存在则杀掉他
System.out.println("thread2休眠过长,主线程杀掉了thread2!");
}
else
System.out.println("主线程没发明thread2,thread2已醒顺序执行竣事了!");
System.out.println("措施竣事按任意键继承!");
try
{
System.in.read();
}
catch (IOException e)
{
System.out.println(e.toString());
}
}//main
}//MultiThread
class ThreadUseExtends extends Thread
//通过担任Thread类,并实现它的抽象要领run()
//适其时候建设这一Thread子类的实例来实现多线程机制
//一个线程启动后(也即进入停当状态)一旦得到CPU将自动挪用它的run()要领
{
ThreadUseExtends(){}//结构函数
public void run()
{
System.out.println("我是Thread子类的线程实例!");
System.out.println("我将挂起10秒!");
System.out.println("回到主线程,请稍等,适才主线程挂起大概还没醒过来!");
try
{
sleep(10000);//挂起5秒
}
catch (InterruptedException e)
{
return;
}
//假如该run()要领顺序执行完了,线程将自动竣事,而不会被主线程杀掉
//但假如休眠时间过长,则线程还存活,大概被stop()杀掉
}
}
class ThreadUseRunnable implements Runnable
//通过实现Runnable接口中的run()要领,再以这个实现了run()要领的类
//为参数建设Thread的线程实例
{
//Thread thread2=new Thread(this);
//以这个实现了Runnable接口中run()要领的类为参数建设Thread类的线程实例
ThreadUseRunnable(){}//结构函数
public void run()
{
System.out.println("我是Thread类的线程实例并以实现了Runnable接口的类为参数!");
System.out.println("我将挂起1秒!");
System.out.println("回到主线程,请稍等,适才主线程挂起大概还没醒过来!");
try
{
Thread.sleep(1000);//挂起5秒
}
catch (InterruptedException e)
{
return;
}
//假如该run()要领顺序执行完了,线程将自动竣事,而不会被主线程杀掉
//但假如休眠时间过长,则线程还存活,大概被stop()杀掉
}
}
//该措施可做的修改如改休眠时间或优先级setPriority()