Runnable与Thread

一、实现多线程的方法

  • 继承Thread类
  • 实现Runnable接口
  • 使用ExecutorService、Callable、Future实现有返回结果的多线程----多线程可以有返回值。
  int taskSize = 5;  
   // 创建一个线程池  
   ExecutorService pool = Executors.newFixedThreadPool(taskSize);  
   // 创建多个有返回值的任务  
   List<Future> list = new ArrayList<Future>();  
   for (int i = 0; i < taskSize; i++) {  
    Callable c = new MyCallable(i + " ");  
    // 执行任务并获取Future对象  
    Future f = pool.submit(c);  
    // System.out.println(">>>" + f.get().toString());  
    list.add(f);  
   }  
   // 关闭线程池  
   pool.shutdown();  
  
   // 获取所有并发任务的运行结果  
   for (Future f : list) {  
    // 从Future对象上获取任务的返回值,并输出到控制台  
    System.out.println(">>>" + f.get().toString());  
   }  `

需要返回值的必须实现Callable,不需要返回值的必须实现Runnable

二、Thread与Runnable区别

  • Thread是类,类只能单继承
  • Runnable是接口,接口可以多实现
  • Runnable可以进行数据共享:
//Runnable
class TestThread implements Runnable{
    private int ticket=5;  
    private String name;  
    public TestThread(String name){  
        this.name=name;  
    }  
    public void run(){  
        for(int i=1;i<=10;i++){  
            if(ticket>0){  
                System.out.println("线程"+name+"卖票"+(ticket--));  
                }  
        }  
    }  
}

public class Demo 
{  
    public static void main(String args[]){  
        TestThread T = new TestThread ("name");    
        Thread T1 = new Thread(T );      
        Thread T2 = new Thread(T );      
        T1.start();  
        T2.start();  
    }  
}
//Thread
class TestThread  extends Thread  
{     
    private int ticket=5;  
    private String name;  
    public TestThread (String name ){  
        this.name=name;  
    }  
    public void run(){  
        for(int i=0;i<10;i++){  
            if(ticket>5){  
                System.out.println("线程"+name+"卖票"+i);  
            }  
        }  
      
    }  
}  
  
public class Demo
{  
    public static void main(String args[]){  
        TestThread A = new TestThread("name1");    
        TestThread B = new TestThread("name2");  
        A.start();  
        B.start();  
    }  
}

抛开运行结果不看,只看上面Thread和Runnable同类Demo的地方,在这里想想为啥说数据共享。

三、Runnable和Thread,run()结束后会自动停止吗?
当线程执行完毕或被其它线程杀死,线程就进入死亡状态,这时线程不可能再进入就绪状态等待执行。
自然终止:正常运行run()方法后终止
异常终止:调用stop()方法让一个线程终止运行或者通过interrupt

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值