您的位置:首页 > 编程语言 > Java开发

java创建多线程的三种方式

2015-09-09 14:23 344 查看
/***************************继承Thread类创建多线程************************/
public class FirstThread extends Thread{
private int i;//继承Thread创建线程不共享实例变量
public void run()
{
for (; i < 10; i++) {
System.out.println(getName()+" "+i);//通过this.getName()获得线程名称
}
}
public static void main(String[] args)
{
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName()+" "+ i);
if(i == 20)
{
new FirstThread().start();
new FirstThread().start();
}
}

}
}


/************************实现Runnable接口创建多线程*************************/
public class SecondThread implements Runnable
{
private int i;//继承Runnable接口共享实例变量
public void run()
{
for(;i < 100; i++)
{
System.out.println(Thread.currentThread().getName()+" "+i);
}
}
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {//继承Runnable接口要通过Tread.currentThread()获得当前进程
System.out.println(Thread.currentThread().getName()+" "+i);
if(i == 20)
{
SecondThread st = new SecondThread();//Runnable对象作为Thread对象的target
new Thread(st, "新线程1").start();
new Thread(st, "新线程2").start();
}
}
}
}


/************************使用Callable和Future创建线程********************************/
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
public class ThirdThread {
public static void main(String[] args)
{	//FutureTask类包装了Callable对象,封装了Callable对象的call()方法。
//call()方法可以有返回值,也可以声明抛出异常。
FutureTask<Integer> task = new FutureTask<Integer>((Callable<Integer>)()->{
int i = 0;
for(; i < 100; i ++)
{
System.out.println(Thread.currentThread().getName()+" 的循环变量i的值:"+i);
}
return i;
});

for (int i = 0; i < 100	; i++) {
System.out.println(Thread.currentThread().getName()+" 的循环变量的值:"+i);
if(i == 20)
{
new Thread(task, "有返回值的线程").start();//task作为Thread类的target
}
}
try
{
System.out.println("子线程的返回值:" + task.get());//get()获取返回值
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: