/** * 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() */ publicsynchronizedvoidstart(){ /** * 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) thrownew 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 */ } } }
privatenativevoidstart0();
/** * 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 publicvoidrun(){ if (target != null) { target.run(); } }
根据Java API : Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread. start()方法会使得该线程开始执行;java虚拟机会自动去调用该线程的run()方法。因此,t.start()会导致run()方法被调用,run()方法中的内容称为线程体,它就是这个线程需要执行的工作。 在start方法里调用了一次start0方法,这个方法是一个只声明未定义的方法,并且使用了native关键字进行定义native指的是调用本机的原生系统函数。所以,调用start方法,会告诉JVM去分配本机系统的资源,才能实现多线程。而如果使用run()来启动线程,就不是异步执行了,而是同步执行,不会达到使用线程的意义。 用start()来启动线程,实现了真正意义上的启动线程,此时会出现异步执行的效果,即在线程的创建和启动中所述的随机性。
publicstaticvoidmain(String args[]){ Acount a = new Acount("brent", 100); BankOperator bko = new BankOperator(a);
Thread t1 = new Thread(bko, "customer1"); Thread t2 = new Thread(bko, "customer2"); Thread t3 = new Thread(bko, "customer3"); Thread t4 = new Thread(bko, "customer4");