1. 继承Thread类,使用这样的办法不可以多个线程共享线程资源
public class myTread extends Thread {
/**
* @param args
*/
private int j=0;
@Override
public void run() {
// TODO Auto-generated method stub
for(int i=0;i<5;i++){
j++;
System.out.println(this.getName()+" "+j);
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
myTread T1= new myTread();
T1.setName("T1");
T1.start();
myTread T2= new myTread();
T2.setName("T2");
T2.start();
}
}
2. 实现Runnable接口,使用这种办法可以共享资源
public class myRunnable implements Runnable {
private int j=0;
@Override
public void run() {
// TODO Auto-generated method stub
for(int i=0;i<5;i++){
j++;
System.out.println(Thread.currentThread().getName()+" "+j);
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
myRunnable mr=new myRunnable();
new Thread(mr,"T1").start();
new Thread(mr,"T2").start();
}
}
注意:使用以上两种办法的时候获取线程名称的方法是有区别的
3. JDK1.5里使用callable类似runnalble不过callable有返回值,也支持异常抛出
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
//使用callable 和 futuretask 来实现多线程
//定义一个类实现callable接口
class goNumber implements Callable<String>
{
//实现call方法并且有返回值
public String call(){
System.out.println(Thread.currentThread().getName()+" print value in internal thread");
return Thread.currentThread().getName()+" returns weihongrao";
}
}
public class mycall {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try{
goNumber go=new goNumber();
FutureTask<String> mytask=new FutureTask<String>(go);
new Thread(mytask,"gotask1").start();
System.out.println("return value is :"+mytask.get());
}catch(Exception e){
System.out.println(e.getMessage());
}
}
}