这里就不多说了,具体就看我写的程序吧!这是通过ArrayList类来统一添加线程,最后用一个特别的调度器线程来根据优先级调度分配给线程的时间。
import java.util.ArrayList;
public class ServerDemo {
public static void main(String[] args){
/*优先级的设定其实并不靠谱,因为这主要依赖于操作系统,
* 即使为最大优先级也不一定会被先执行,当把下面这句设定
* 优先级的句子注释掉,会发现系统默认main线程的优先级
* 最高,反正以我之见,依赖底层实现的程序的运行结果多有
* 不确定。这可要人为地小心了,要不然干嘛还要引入同步
* 系统默认被创建的线程的优先级比创建它的线程低,设定
* 优先级一定要在run方法中使线程发生中断,这样才能让其他
* 的线程也可以获得CPU的时间!要不然就会等到执行结束
* 才会让出系统的控制权。
*/
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
Scheduler sch = new Scheduler();
sch.setDaemon(true);
sch.start();
TestThread t1 = new TestThread("T1");
t1.start();
sch.addThread(t1); //改变线程t1的优先级
TestThread t2 = new TestThread("T2");
t2.start();
sch.addThread(t2); //改变线程t2的优先级
TestThread t3 = new TestThread("T3");
t3.start();
sch.addThread(t3); //改变线程t3的优先级
System.out.println("ok");
}
}
/*
* 这是一个调度器线程,主要作用是通过将线程添加进数组中,并依次改变它们的优先
* 级来保证它们的执行顺序的先后,可是发现在运行当中,还是没有依次执行,很疑惑
*
*/
class Scheduler extends Thread {
private ArrayList<Thread> list = new ArrayList<Thread>();
private static final int DEFAULT_TIME_SLICE=10;
private int slice;
private int activeIndex=0;
private Thread activeThread;
public Scheduler(){
this.slice=DEFAULT_TIME_SLICE;
this.setName("Scheduler");
}
public Scheduler(int slice){
this.slice=slice;
this.setName("Scheduler");
}
public void addThread(Thread t){
if(t==null)
System.out.println("the Thread is null");
t.setPriority(2);
list.add(t);
}
private void schedulerSleep(){
try{
Thread.sleep(slice);
}catch(InterruptedException e){
e.printStackTrace();
}
}
@Override
public void run(){
Thread current;
this.setPriority(6); // make sure that the schedulerThread can execute firstly,
// so it can add the thread in list work rightly
while(true){
current = findNext();
activeThread = current; // get the thread from the list
activeIndex = list.indexOf(activeThread); //????activeThread or current try to do it
if((current != null)&&(current.isAlive())){
activeThread.setPriority(4);
}
schedulerSleep();
if((current != null)&&(current.isAlive())){
activeThread.setPriority(2);
}
System.out.println(" end of "+Thread.currentThread().getName());
}
}
Thread findNext(){
Thread current;
int index=0;
if(activeIndex>=(list.size()-1)&&list.size()!=0)index=0;
else if(list.size()==0)return null;
//如果当前线程还处于有效状态,则继续执行当前线程
else if(activeThread != null&&activeThread.isAlive()) index = activeIndex ;
else index = activeIndex +1;
current = list.get(index); //返回指定的线程
return current;
}
}
class TestThread extends Thread{
public TestThread(String name){
this.setName(name);
}
public void run(){
System.out.println("current name:"+
this.getName()+
" Priority:"+this.getPriority());
}
}