码迷,mamicode.com
首页 > 编程语言 > 详细

Java中的Thread与Runnable的区别

时间:2014-10-14 18:09:09      阅读:206      评论:0      收藏:0      [点我收藏+]

标签:ar   java   for   sp   div   art   代码   ad   bs   

1、thread不能设置共享资源、runnable可以设置共享资源
2、代码风格与结构,ruannbale更好些
3、
 
public class TestThread extends Thread {
    private int count = 5;
    
    @Override
    public void run() {
          for(int i=0; i<10; i++) {
              if(this.count>0) {
                   System.out.println(Thread.currentThread().getName + "-----" +this.count--);
              }
          }
    }
    
    public static void main(String[] args) {
         TestThread test1 = new TestThread();
          test1.start();
 
         
         TestThread test2 = new TestThread();
          test2.start();
    }
}
 
=============
 
public class TestRunnable implements Runnable {
    private int count = 5;
 
    public TestRunnable() {
         
    }
 
    @Override
    public void run() {
          for(int i=0; i< 20; i++) {
              if(this.count>0) {
                   System.out.println(Thread.currentThread().getName() + "----" + this.count--);
              }
          }
    }
}
 
public class Test {
    public static void main(String[] args) {
          TestRunnable tr = new TestRunnable();
           new Thread(tr).start("A");
           new Thread(tr).start("B");   
    }
 
}

Java中的Thread与Runnable的区别

标签:ar   java   for   sp   div   art   代码   ad   bs   

原文地址:http://www.cnblogs.com/Eric-Zxl/p/4024594.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!