Class:Thread
interface:Runnerable
实现Runnerable接口比继承Thread类所具有的优势:
1)适合多个相同的程序代码的线程去处理同一个资源
2)可以避免JAVA中单继承的限制
3)增加程序的健壮性,代码可以被多个线程共享,代码和数据独立
所以,推荐实现接口
主程序:
<span style="font-size:24px;">import java.util.*;
import java.lang.*;
public class Generaldemo{
public static void main(String[] args)
{
myThread mthread = new myThread();
mythread2 th2 = new mythread2();
Thread r = new Thread(th2);
mthread.start(); //启动一个进程
r.start(); //启动另一个进程
for(int i=0;i<10000;i++)
{
System.out.println(Thread.currentThread().getName()+":"+i);
try{
Thread.sleep(5);
}catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
}
</span>
线程1:
<span style="font-size:24px;">public class myThread extends Thread{
public void run() {
for(int i=0;i<10000;i++)
{
System.out.println(Thread.currentThread().getName()+":"+i);
try{
Thread.sleep(5);
}catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
}</span>
线程2:
<span style="font-size:24px;">import java.lang.*;
public class mythread2 implements Runnable{
public void run(){
for(int i=0;i<10000;i++)
{
System.out.println(Thread.currentThread().getName()+":"+i);
try{
Thread.sleep(5);
}catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
}</span>
多线程的优先级设定:
package threaddemo;
class ThRun implements Runnable{
public void run()
{
for(int i=0;i<5;i++)
{
try {
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName()+":"+i);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} //sleep->1s
}
}
}
public class mythread4 {
public static void main(String[] args) {
Thread t1 = new Thread(new ThRun(),"A");
Thread t2 = new Thread(new ThRun(),"B");
Thread t3 = new Thread(new ThRun(),"C");
t1.setPriority(Thread.MIN_PRIORITY);
t2.setPriority(Thread.NORM_PRIORITY);
t3.setPriority(Thread.MAX_PRIORITY);
t1.start();
t2.start();
t3.start();
}
}
输出结果:
<img src="https://img-blog.csdn.net/20140919162841444?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvTWFya19fWmVuZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="" />
可以明显的看出C线程的优先级要高于B,B要高于A