1.使用普通内部类继承Thread类
public class ThreadTestOne {
private int countDown = 5;
private Inner inner;
private class Inner extends Thread{
Inner(String name){
super(name);
start();
}
public void run(){
while(true){
System.out.println(this);
if(--countDown == 0)
return;
try{
sleep(10);
}catch(InterruptedException e){
throw new RuntimeException(e);
}
}
}
public String toString(){
return "#"+getName()+":"+countDown;
}
}
public ThreadTestOne(String name){
inner = new Inner(name);
}
}
2.使用匿名内部类构造Thread类,重写run()方法
public class ThreadTestTwo {
private int countDown = 5;
private Thread t;
public ThreadTestTwo(String name){
t = new Thread(name){
public void run(){
while(true){
System.out.println(this);
if(--countDown == 0)
return;
try{
sleep(10);
}catch(InterruptedException e){
throw new RuntimeException(e);
}
}
}
public String toString(){
return "#"+getName()+":"+countDown;
}
};
t.start();
}
}
3.使用普通内部类实现Runnable类
public class RunnableTestOne {
private int countDown = 5;
private Inner inner;
private class Inner implements Runnable{
Thread t;
Inner(String name){
t = new Thread(this,name);
t.start();
}
public void run(){
while(true){
System.out.println(this);
if(--countDown == 0)
return;
try{
Thread.sleep(10);
}catch(InterruptedException e){
throw new RuntimeException(e);
}
}
}
public String toString(){
return "#"+Thread.currentThread().getName()+":"+countDown;
}
}
public RunnableTestOne(String name){
inner = new Inner(name);
}
}
4.使用匿名内部类构造Thread类,参数1构造一个Runnable对象,参数2指明线程名称
public class RunnableTestTwo {
private int countDown = 5;
private Thread t;
public RunnableTestTwo(String name){
t = new Thread(new Runnable(){
public void run(){
while(true){
System.out.println(this);
if(--countDown == 0)
return;
try{
Thread.sleep(10);
}catch(InterruptedException e){
throw new RuntimeException(e);
}
}
}
public String toString(){
return "#"+Thread.currentThread().getName()+":"+countDown;
}
},name);
t.start();
}
}
5.使用局部内部类,即在方法内部构造Thread类,重写run()方法
public class ThreadMethod {
private int countDown = 5;
private Thread t;
private String name;
public ThreadMethod(String name){
this.name = name;
}
public void runThread(){
if(t == null){
t = new Thread(name){
public void run(){
while(true){
System.out.println(this);
if(--countDown == 0)
return;
try{
sleep(10);
}catch(InterruptedException e){
throw new RuntimeException(e);
}
}
}
public String toString(){
return "#"+getName()+":"+countDown;
}
};
t.start();
}
}
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-02 07:00:55