Java创建线程的两种方式和主要区别

通过使用Callable创建线程的方式本文中不在讨论,可以参考:http://blog.csdn.net/dax1n/article/details/60322067


方式1: 实现Runnable接口创建线程


public class RunnableDemo implements Runnable {

	@Override
	public void run() {
		// TODO Auto-generated method stub
		System.out.println("Runnable ...");
	}

	public static void main(String[] args) {
		
		new Thread(new RunnableDemo()).start();
		
		
	}
}


首先看一下Runnable接口声明;

public interface Runnable {
    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see     java.lang.Thread#run()
     */
    public abstract void run();
}

我们可以实现Runnable接口在run方法中完成自己的计算任务。

接下来需要将Runnable实例传给Thread实例,然后启动。接下来看看Thread的实现:


/**
 * 
 * 省略了大部门代码,具体代码看JDK源码
 * 
 * @author Daxin
 *
 */
public class Thread implements Runnable {

    private char        name[];
    private int         priority;

    /* Whether or not the thread is a daemon thread. */
    private boolean     daemon = false;

    /* What will be run. */
    private Runnable target;


    /*
     * The requested stack size for this thread, or 0 if the creator did
     * not specify a stack size.  It is up to the VM to do whatever it
     * likes with this number; some VMs will ignore it.
     */
    private long stackSize;


    /**
     * The argument supplied to the current call to
     * java.util.concurrent.locks.LockSupport.park.
     * Set by (private) java.util.concurrent.locks.LockSupport.setBlocker
     * Accessed using java.util.concurrent.locks.LockSupport.getBlocker

    /**
     * The minimum priority that a thread can have.
     */
    public final static int MIN_PRIORITY = 1;

   /**
     * The default priority that is assigned to a thread.
     */
    public final static int NORM_PRIORITY = 5;

    /**
     * The maximum priority that a thread can have.
     */
    public final static int MAX_PRIORITY = 10;

    public static native void yield();


    private native void start0();

    /**
     * If this thread was constructed using a separate
     * <code>Runnable</code> run object, then that
     * <code>Runnable</code> object's <code>run</code> method is called;
     * otherwise, this method does nothing and returns.
     * <p>
     * Subclasses of <code>Thread</code> should override this method.
     *
     * @see     #start()
     * @see     #stop()
     * @see     #Thread(ThreadGroup, Runnable, String)
     */
    @Override
    public void run() {
        if (target != null) {
            target.run();
        }
    }
    
    //省略其他代码...
    
    
    
    /**
     * Causes this thread to begin execution; the Java Virtual Machine
     * calls the <code>run</code> method of this thread.
     * <p>
     * The result is that two threads are running concurrently: the
     * current thread (which returns from the call to the
     * <code>start</code> method) and the other thread (which executes its
     * <code>run</code> method).
     * <p>
     * It is never legal to start a thread more than once.
     * In particular, a thread may not be restarted once it has completed
     * execution.
     *
     * @exception  IllegalThreadStateException  if the thread was already
     *               started.
     * @see        #run()
     * @see        #stop()
     */
    public synchronized void start() {
        /**
         * This method is not invoked for the main method thread or "system"
         * group threads created/set up by the VM. Any new functionality added
         * to this method in the future may have to also be added to the VM.
         *
         * A zero status value corresponds to state "NEW".
         */
        if (threadStatus != 0)
            throw new IllegalThreadStateException();

        /* Notify the group that this thread is about to be started
         * so that it can be added to the group's list of threads
         * and the group's unstarted count can be decremented. */
        group.add(this);

        boolean started = false;
        try {
            start0();//调用系统的本地方法启动线程
            started = true;
        } finally {
            try {
                if (!started) {
                    group.threadStartFailed(this);
                }
            } catch (Throwable ignore) {
                /* do nothing. If start0 threw a Throwable then
                  it will be passed up the call stack */
            }
        }
    }

    private native void start0();

}


Thread类也实现了Runnable接口,所以Thread中也重写了Runnable的run方法,在Runnable的run方法中调用我们自己的run方法:

    @Override
    public void run() {
        if (target != null) {
            target.run();
        }
    }

线程的启动调用start方法,在Thread的start方法中调用了本地方法start0。

 public synchronized void start() {
        /**
         * This method is not invoked for the main method thread or "system"
         * group threads created/set up by the VM. Any new functionality added
         * to this method in the future may have to also be added to the VM.
         *
         * A zero status value corresponds to state "NEW".
         */
        if (threadStatus != 0)
            throw new IllegalThreadStateException();

        /* Notify the group that this thread is about to be started
         * so that it can be added to the group's list of threads
         * and the group's unstarted count can be decremented. */
        group.add(this);

        boolean started = false;
        try {
            start0();//调用系统的本地方法启动线程
            started = true;
        } finally {
            try {
                if (!started) {
                    group.threadStartFailed(this);
                }
            } catch (Throwable ignore) {
                /* do nothing. If start0 threw a Throwable then
                  it will be passed up the call stack */
            }
        }
    }

系统本地方法真正启动线程:

 private native void start0();


然而实现线程的第二种方式便是直接继承Thread类然后直接把自己计算的业务直接写在Thread的run方法中:

public class ThreadDemo extends Thread {

	@Override
	public void run() {
		// TODO Auto-generated method stub
		System.out.println("ThreadDemo ... ");
	}

	public static void main(String[] args) {
		new ThreadDemo().start();
	}

}

直接将自己的计算任务写在Thread的run中,然后直接启动。


关于这两种方式创建线程的区别:


首先模拟一下售票系统:

Runnable方式模拟:

public class RunnableDemo implements Runnable {

	//支持共享的成员变量
	int sum = 10;

	@Override
	public void run() {

		// synchronized如果放在此处的话,一个窗口全把票都卖完了,其余两个窗口没有机会出售。
		// 因为当一个线程在此处获取到所之后,不执行完代码不会释放锁,不释放锁别个线程进不来。(synchronized代码块执行完毕才能释放锁)
		while (sum > 0) {
			synchronized (String.class) {// 注意synchronized 的位置

				if (sum <= 0)// 需要判断,因为while (sum > 0)没有锁,所以可以并行执行不安全
					break;
				int tmp = sum--;
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				System.out.println(Thread.currentThread().getName() + "窗口             " + tmp);
			}
		}

	}

	public static void main(String[] args) {

		RunnableDemo run = new RunnableDemo();
		new Thread(run, "1").start();
		new Thread(run, "2").start();
		new Thread(run, "3").start();

	}
}

这种方式创建三个线程,这三个线程共享一个run实例的sum成员变量,所以正确输出结果:

1窗口             10
1窗口             9
3窗口             8
2窗口             7
3窗口             6
1窗口             5
3窗口             4
2窗口             3
3窗口             2
3窗口             1


然而使用Thread也按照上面代码实现的话,代码如下:

public class ThreadDemo extends Thread {

	public ThreadDemo() {

	}

	public ThreadDemo(String name) {
		super(name);// 设置线程名字
	}

	int sum = 10;

	@Override
	public synchronized void run() {

		while (sum > 0) {
			synchronized (String.class) {
				
				if (sum <= 0)
					break;
				int tmp = sum--;
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				System.out.println(Thread.currentThread().getName() + "             " + tmp);

			}

		}
	}

	public static void main(String[] args) {
		ThreadDemo t1 =new ThreadDemo("1       ");  t1.start();
		ThreadDemo t2 =new ThreadDemo("2       ");  t2.start();
		ThreadDemo t3 =new ThreadDemo("3       ");  t3.start();
	}

}

创建了ThreadDemo实例,而每一个实例各自存在一个sum成员,所以出售了30张票,结果不正确:

1窗口             10
1窗口             9
3窗口             10
2窗口             10
2窗口             9
3窗口             9
1窗口             8
3窗口             8
2窗口             8
3窗口             7
1窗口             7
1窗口             6
3窗口             6
2窗口             7
2窗口             6
3窗口             5
1窗口             5
3窗口             4
2窗口             5
3窗口             3
1窗口             4
3窗口             2
2窗口             4
2窗口             3
2窗口             2
3窗口             1
1窗口             3
1窗口             2
2窗口             1
1窗口             1


这样的话?难道继承Thread就无法实现售票系统了吗?答案:当然是可以实现的,但是要实现的话,就需要解决sum成员属性支持共享的问题:

方式1:

		ThreadDemo t=new ThreadDemo("1       ");
		
		
		Thread t1=new Thread(t);
		Thread t2=new Thread(t);
		Thread t3=new Thread(t);

		t1.start();
		t2.start();
		t3.start();

方式2:内部类共享

public class MovieTicket {

	int sum = 10;

	class Seller extends Thread {

		public Seller() {
			// TODO Auto-generated constructor stub
		}

		public Seller(String name) {
			// TODO Auto-generated constructor stub
			super(name);
		}

		@Override
		public void run() {
			while (sum > 0) {
				synchronized (String.class) {
					
					if (sum <= 0) {
						break;
					}
					int tmp = sum--;
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					System.out.println(Thread.currentThread().getName() + "           " + tmp);

				}

			}

		}
	}

	public static void main(String[] args) {
		MovieTicket mt = new MovieTicket();

		Seller s1 = mt.new Seller("1");
		Seller s2 = mt.new Seller("2");
		Seller s3 = mt.new Seller("3");

		s1.start();
		s2.start();
		s3.start();

	}

}


这样的话sum就是三个线程共享的成员了,所以就可以实现售票系统了。



总结:

两个不同的实现多线程,一个是多个线程共同完成一个任务(第一个售票系统)。一个是多个线程分别完成自己的任务(第二个售票系统),

其实在实现一个任务用多个线程来做也可以用继承Thread类来实现只是比较麻烦(第三个售票系统),一般我们用实现Runnable接口来实现,简洁明了。

实现接口也可以为该类继承某类实现增强时留有余地(java单继承)。



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值