java中线程的实现主要有两种方法,一种是继承Thread类,另外一种是实现Runnable接口。
其实有三种方法,除了上述的两种,还有一种是实现Callable接口。
1.继承Thread 类
package xiancheng;
public class Mythread extends Thread {
private String name;
public Mythread(String name) {
this.name = name;
}
public void run() { //线程中必须覆写Thread的run方法
for(int i=1; i<=3; i++) {
System.out.println(name+"运行,i="+i);
}
}
}
package xiancheng;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Mythread m = new Mythread("线程1");
Mythread n = new Mythread("线程2");
m.run();
n.run();
System.out.println("______________________");
m.start(); //要想启动多线程,必须用Thread中的start方法
n.start();
}
}
Mythread类继承了Thread类,来实现多线程,在Main方法中可以看到,首先实例化Mythread的对象,但是如果直接用run()方法来调用会出现什么结果呢?
运行可知,用run()方法不能实现多线程的启用,必须借助start()方法才能让多线程正常启用。run()方法时顺序式的执行方式,是先执行完m对象之后再执行n对象。而start()方法不然,是两个对象交错运行,成功启动了多线程。
2.使用Runnable接口
package xiancheng;
class Mythread1 implements Runnable{
public void run() {
for(int i=0; i<=3; i++) {
System.out.println(Thread.currentThread().getName()+"运行,i="+i);
}
}
}
package xiancheng;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Mythread1 my = new Mythread1();
//Thread i = new Thread(my);
//i.start()
new Thread(my,"线程").start();
new Thread(my).start();
Thread t = new Thread(my);
t.isAlive();
System.out.println(t.isAlive());
}
}
使用Runnable接口,程序主体和使用Thread方法大体一样。但是有一点需要注意,使用Runnable时,实例化对象之后必须实例化Thread类对象。
最后的isAlive()方法时检验多线程是否存在的。
Mythread1 my = new Mythread1();
//Thread i = new Thread(my);
//i.start()
new Thread(my,"线程").start();
new Thread(my).start();
这是两种实例化Thread类对象的方法,第二种直接运用匿名对象来实例化。
3.实现Callable接口
- 实现Runnable接口可以避免由于java单继承带来的局限,但是实现Runnable接口,其中的run()方法不能返回操作结果。为了解决这样的问题,从JDK1.5开始对于多线程的实现提供了一的新的接口:Callable,接口定义如下:
public interface Callable<V>{
public V call() throws Exception;
}
- Callable 具体使用方法:
class MyThread implements Callable{
private int ticket = 5;
@Override
public Object call() throws Exception {
for(int x=0; x<100; x--){
if(this.ticket > 0){
System.out.println("卖票:ticket= "+this.ticket--);
}
}
return "票已卖光";
}
}
public class ExecDemo {
public static void main(String[] args) {
MyThread mt1 = new MyThread();
MyThread mt2 = new MyThread();
FutureTask<String> fu = new FutureTask<String>(mt1);
FutureTask<String> fu2 = new FutureTask<String>(mt1);
new Thread(fu).start();
new Thread(fu2).start();
System.out.println("A线程的返回结果: "+fu.get());
System.out.println("B线程的返回结果: "+fu2.get());
}
}
- 实现Callable接口,用FutureTask类接受Callable接口的实例,然后利用Thread类来实现多线程的启动,如果想要接受返回结果,就可以调用Future接口中的get()方法。