在启动线程时是应该调用线程的run()方法还是start()方法?

来源:互联网 发布:c语言简单小程序 编辑:程序博客网 时间:2024/05/01 15:11

首先请看一下如下的代码:

设计4个线程,其中两个线程每次对j增加1,另外两个线程对j每次减少1。写出程序。
以下程序使用内部类实现线程,对j增减的时候没有考虑顺序问题。
public class ThreadTest1{
 private int j;
 public static void main(String[] args){
  ThreadTest1 tmp = new ThreadTest1();
  for(int i = 0;i < 2;i++ ){
   Thread t1 = new Thread(tmp.new Add());
   t1.run();
   Thread t2 = new Thread(tmp.new Delete());
   t2.start();
  }
 }
 
 private synchronized void add(){
  j ++;
  System.out.println(Thread.currentThread().getName() + ": " + j);
 }
 private synchronized void delete(){
  j --;
  System.out.println(Thread.currentThread().getName() + ": " + j);
 }
 
 class Add implements Runnable{
  public void run(){
   for(int i = 0;i < 5;i++ ){
    add();
   }
  }
 }
 class Delete implements Runnable{
  public void run(){
   for(int i = 0;i < 5;i++ ){
    delete();
   }
  }
 }
}

通过改动把t1.run()处该为t1.start(),比较两次运行的结果,你会发现两次运行的结果很不一样,下面是两次运行的结果:

Thread-0: 1
Thread-2: 2
Thread-1: 1
Thread-3: 0
Thread-0: 1
Thread-2: 2
Thread-1: 1
Thread-3: 0

 

main: 1
main: 2
main: 3
main: 4
main: 5
main: 6
main: 7
main: 8
main: 9
main: 10
Thread-1: 9
Thread-1: 8
Thread-1: 7
Thread-1: 6
Thread-1: 5
Thread-3: 4
Thread-3: 3
Thread-3: 2
Thread-3: 1
Thread-3: 0


原因分析:

start()方法:用来启动一个线程,这时此线程处于就绪状态,然后通过调用此线程的run()方法来完成线程的运行操作。

run()方法:这只是一个方法,直接调用该方法只是把该方法的函数体给执行了一遍,并没真正启动一个线程,所以上面第二次运行的结果中会有main:线程

原创粉丝点击