很久没有写java程序了,由于为了改变目前的状况,打算花两天时间学习一下java的线程开发和高并发。

    线程开发使用thread类,或者runnable接口,而且thread类也是实现了runnable接口的。

    先来个小甜点作为开始,如下为创建多个线程,并且同时处理。

package firstThreadStudy;

public class MyThread extends Thread {
	public MyThread(){
		
		System.out.println("MyThread currentThread().getName()="+Thread.currentThread().getName());
		System.out.println("MyThread this.getName=" + this.getName());
		
	}
	@Override
	public void run(){
		
		System.out.println("run currentThread().getName()="+Thread.currentThread().getName());
		System.out.println("run this.getName="+this.getName());
		int i=2;
		while(i>0)
		{
			System.out.println("run " + this.getName() + ": i = " + (i--));
			try{
			Thread.sleep(1000);
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
		}
		
		
	}
}


测试类:

package firstThreadStudy;

public class Test2MyThread {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		MyThread boy = new MyThread();
		boy.setName("boy");
		MyThread girl = new MyThread();
		girl.setName("girl");
		Thread car = new Thread(girl);
		car.setName("car");
		boy.start();
		car.start();
		System.out.println("method end");
	}

}

   

另外,特别补充说明

Thread.currentThread().getName()

this.getName()

的区别,前者表示调用当前方法的线程名,后者表示当前线程对象名。可能不是很好理解,根据下面输出解释会比较好理解些。

    上列的输出可能性之一如下(线程是随机调度的):

MyThread currentThread().getName()=main
MyThread this.getName=Thread-1
MyThread currentThread().getName()=main
MyThread this.getName=Thread-2
run currentThread().getName()=boy
run this.getName=boy
method end
run currentThread().getName()=car
run boy: i = 2
run this.getName=girl
run girl: i = 2
run girl: i = 1
run boy: i = 1

girl对象和 car对象是两个对象,因为this.getName()是girl对象中的代码,所以this访问的girl对象。

Thread.currentTread().getName()指当前调用方法的线程对象,不是指gril对象,而是car对象,girl对象只是一个传入其中的参数,girl对象的run方法是由car对象的start()方法触发调度,并不是girl对象的start()触发。gril虽然是个线程对象,但是并未启动,所以其本身并没有线程,而是依托在car线程中执行。

     额,我觉得说了上面这些废话,应该能解释清楚。