多线程

public class TraditionalThread {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
	
		Thread thread = new Thread(){
			@Override
			public void run() {
				while(true){
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println("1:" + Thread.currentThread().getName());
					System.out.println("2:" + this.getName());
				}
			}
		};
		thread.start();
		
		Thread thread2 = new Thread(new Runnable(){
			@Override
			public void run() {
				while(true){
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println("1:" + Thread.currentThread().getName());

				}				
				
			}
		});
		thread2.start();
		
		new Thread(
				new Runnable(){
					public void run() {
						while(true){
							try {
								Thread.sleep(500);
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
							System.out.println("runnable :" + Thread.currentThread().getName());

						}							
					}
				}
		){
			public void run() {
				while(true){
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println("thread :" + Thread.currentThread().getName());

				}	
			}
		}.start();
	}
}

启动线程肯定要用start()方法。当用start()开始一个线程后,线程就进入就绪状态,使线程所代表的虚拟处理机处于可运行状态,

这意味着它可以由JVM调度并执行。这并不意味着线程就会立即运行。当cpu分配给它时间时,

才开始执行run()方法(如果有的话)。START()是方法,它调用RUN()方法.而RUN()方法是你必须重写的. run()方法中包含的是线程的主体。


继承Thread类的启动方式:

public class ThreadStartTest { 

    public static void main(String[] args) { 

        ThreadTest tt = new ThreadTest();// 创建一个线程实例 

         tt.start();  // 启动线程 

    } 

实现Runnable接口的启动方式:

public class RunnableStartTest { 

    public static void main(String[] args) { 

       Thread t = new Thread(new RunnableTest());    // 创建一个线程实例

        t.start();  // 启动线程 

    } 

实际上这两种启动线程的方式原理是一样的。首先都是调用本地方法启动一个线程,

其次是在这个线程里执行目标对象的run()方法。那么这个目标对象是什么呢?

为了弄明白这个问题,我们来看看Thread类的run()方法的实现:

public void run() { 

    if (target != null) { 

        target.run(); 

    } 

当我们采用实现Runnable接口的方式来实现线程的情况下,在调用new Thread(Runnable target)构造器时,

将实现Runnable接口的类的实例设置成了线程要执行的主体所属的目标对象target,

当线程启动时,这个实例的 run()方法就被执行了。当我们采用继承Thread的方式实现线程时,

线程的这个run()方法被重写了,所以当线程启动时,执行的是这个对象自身的 run()方法。

总结起来就一句话,如果我们采用的是继承Thread类的方式,那么这个target就是线程对象自身,

如果我们采用的是实现Runnable接口的方式,那么这个target就是实现了Runnable接口的类的实例。


你可能感兴趣的:(多线程)