前言
原创文章欢迎转载,请保留出处。
若有任何疑问建议,欢迎回复。
邮箱:Maxwell_nc@163.com
在JAVA中,简单地实现程序多线程的方法有两种,一种是继承Thread类,另一种是实现Runnale接口。
继承方法
首先,创建一个类继承Thread类,覆写run()方法:
class ChildThread extends Thread
{
public void run()
{
//这里写需要线程去处理的代码
while(true)
{
System.out.println(this.getName()+"正在运行");
try
{
Thread.currentThread().sleep(1);
}
catch (InterruptedException e)
{
System.out.println("出现中断异常");
}
}
}
}
class ThreadDemo
{
public static void main(String[] args)
{
//创建线程
ChildThread ct1 = new ChildThread();
ChildThread ct2 = new ChildThread();
//启动线程
ct1.start();
ct2.start();
//设置线程优先级 0 - 10 默认5
ct1.setPriority(5);
ct2.setPriority(5);
Thread.currentThread().setPriority(5);
while(true)
{
System.out.println("主线程正在运行");
try
{
Thread.currentThread().sleep(1);
}
catch (InterruptedException e)
{
System.out.println("出现中断异常");
}
}
}
}
这里要注意,启动线程是调用start()方法,而不是调用run()。
如果调用run()方法,会执行run()方法中的内容,但不会启动线程。
另外要停止run()线程,不能使用stop()方法,该方法已经过时,只有等run()方法结束。
若程序处于冻结状态,可以使用Thread.interrupt()产生中断,强制使其进入运行状态。
实现方法
第二种方法是实现Runnable接口,这个方法可以解决单继承的问题,实际上Thread类就是实现了Runnale接口
使用方法和继承的一样,复写run()方法。调用start()方法启动,不过要注意创建线程的方法稍微有点不同。
class ChildThread implements Runnable
{
public void run()
{
//这里写需要线程去处理的代码
while(true)
{
//这里不能使用this.getName(),因为那是Thread类中的方法
System.out.println(Thread.currentThread().getName()+"正在运行");
try
{
Thread.currentThread().sleep(1);
}
catch (InterruptedException e)
{
System.out.println("出现中断异常");
}
}
}
}
class ThreadDemo
{
public static void main(String[] args)
{
//创建线程,调用Thread的构造方法
//因为本身ChildThread类并不具有线程特性的
ChildThread ct = new ChildThread();
Thread t1 = new Thread(ct);
Thread t2 = new Thread(ct);
//启动线程
t1.start();
t2.start();
//设置线程优先级 0 - 10 默认5
t1.setPriority(5);
t2.setPriority(5);
Thread.currentThread().setPriority(5);
while(true)
{
System.out.println("主线程正在运行");
try
{
Thread.currentThread().sleep(1);
}
catch (InterruptedException e)
{
System.out.println("出现中断异常");
}
}
}
}
上述代码均由本人编写及测试,测试环境为JDK1.6,新的版本或者旧的JDK版本不一定适用。
运行效果如下:
由于采用了while(true),可以使用Ctrl+C终止程序运行。