1.实现线程的第二种方法
提供一个实现接口Runnable的类作为线程的目标对象,在初始化一个Thread类或者Thread子类的线程对象时,把目标对象传递给这个线程实例,由该目标对象提供线程体
class RunnableImpl implements Runnable{
public void run(){
for(int i = 0 ; i < 100 ; i ++ ;){
System.out.println("Runnable-->" + i);
}
}
}class Test{
public static void main (String args[]){
//生成一个Runnable接口实现类的对象
RunnableImpl ri = new RunnableImpl();
//生成一个Thread对象,并将Runnable接口实现类的对象作为参数传递给Thread对象
Thread t = new Thread();
//通知Thread对象,执行start方法
t.start();
}
}
在实际开发过程中更倾向于第二种做法,因为第一种继承Thread只有一次机会,继承Thread就不可以继承其他的(单继承)
2.控制线程的常用方法
。中断线程
—— Thread.sleep(); // Thread.sleep(2000);在线程体中sleep后面要设置一个参数(2000毫秒)sleep(2000)之后还要过一小段时间才可以运行,因为线程要抢占CPU
测试:
class RunnableImpl implements Runnable{
public void run(){
for(int i = 0 ; i < 100 ; i ++ ;){
System.out.println("Runnable-->" + i);
if(i == 50){
try{
Thread.sleep(2000);
}
catch(Exception e){
System.out.println(e);
}
}
}
}
}class Test{
public static void main (String args[]){
//生成一个Runnable接口实现类的对象
RunnableImpl ri = new RunnableImpl();
//生成一个Thread对象,并将Runnable接口实现类的对象作为参数传递给Thread对象
Thread t = new Thread();
//通知Thread对象,执行start方法
t.start();
}
}——Thread.yield(); // 执行到这一行自动让出CPU,然后两个线程在同时抢占CPU,有可能还是这个线程抢到CPU
。设置线程的优先级
——getPriority();
——setPriority() ;
class Test{
public static void main (String args[]){
//生成一个Runnable接口实现类的对象
RunnableImpl ri = new RunnableImpl();
//生成一个Thread对象,并将Runnable接口实现类的对象作为参数传递给Thread对象
//线程的优先级最大是10,最小是1,可以使用Thread所提供的静态常量来设置线程的优先级;
//<span style="color:#ff0000;">注意:线程的优先级越高,执行的概率越大(注意是概率,并不是一定先执行)</span>
//t.setPriority(Thread.MAX_PRIORITY);//设置最大优先级
t.setPriority(Thread.MIN_PRIORITY);//设置最小优先级
Thread t = new Thread();
//通知Thread对象,执行start方法
t.start();
System.out.println(t.getPriority());
}
}原文:http://blog.csdn.net/u011742151/article/details/41576383