Java中多线程的应用是非常多的,我们在Java中又该如何去创建线程呢?
http://www.jianshu.com/p/40d4c7aebd66
1 public class FirstThreadTest extends Thread{
2 int i = 0;
3 //重写run方法,run方法的方法体就是现场执行体
4 public void run()
5 {
6 for(;i<100;i++){
7 System.out.println(getName()+" "+i);
8
9 }
10 }
11 public static void main(String[] args)
12 {
13 for(int i = 0;i< 100;i++)
14 {
15 System.out.println(Thread.currentThread().getName()+" : "+i);
16 if(i==20)
17 {
18 //创建实例,并调用其start()方法启动线程
19 new FirstThreadTest().start();
20 new FirstThreadTest().start();
21 }
22 }
23 }
24 }
1 public class RunnableThreadTest implements Runnable
2 {
3 private int i;
4 //重写run()方法
5 public void run()
6 {
7 for(i = 0;i <100;i++)
8 {
9 System.out.println(Thread.currentThread().getName()+" "+i);
10 }
11 }
12 public static void main(String[] args)
13 {
14 for(int i = 0;i < 100;i++)
15 {
16 System.out.println(Thread.currentThread().getName()+" "+i);
17 if(i==20)
18 {
19 //用实现类的对象作为参数传入new Thread(Runnable obj)来创建Thread对象,然后调用start()方法启动线程
20 RunnableThreadTest rtt = new RunnableThreadTest();
21 new Thread(rtt,"新线程1").start();
22 new Thread(rtt,"新线程2").start();
23 }
24 }
25 }
26 }
1 public class CallableThreadTest implements Callable<Integer>
2 {
3
4 public static void main(String[] args)
5 {
6 CallableThreadTest ctt = new CallableThreadTest();
7 FutureTask<Integer> ft = new FutureTask<>(ctt);
8 for(int i = 0;i < 100;i++)
9 {
10 System.out.println(Thread.currentThread().getName()+" 的循环变量i的值"+i);
11 if(i==20)
12 {
13 new Thread(ft,"有返回值的线程").start();
14 }
15 }
16 try
17 {
18 System.out.println("子线程的返回值:"+ft.get());
19 } catch (InterruptedException e)
20 {
21 e.printStackTrace();
22 } catch (ExecutionException e)
23 {
24 e.printStackTrace();
25 }
26 }
27
28 @Override
29 public Integer call() throws Exception
30 {
31 int i = 0;
32 for(;i<100;i++)
33 {
34 System.out.println(Thread.currentThread().getName()+" "+i);
35 }
36 return i;
37 }
38 }
采用实现Runnable、Callable接口的方式创见多线程时,优势是:
劣势是:
使用继承Thread类的方式创建多线程时优势是:
劣势是: