多线程入门,线程isAlive 方法,this与Thread.currentThread() 的区别,线程优先级,线程运行快慢测试

package test;

public class Test {

	public static void main(String[] args) {
		System.out.println(Thread.currentThread().getName());
	}

}

 

只有thread 类才有start 方法

public class MyRunnable implements Runnable {
	@Override
	public void run() {
		System.out.println("运行中!");
	}
}
public class Run {

	public static void main(String[] args) {
		Runnable runnable=new MyRunnable();
		Thread thread=new Thread(runnable);//只有thread 类才有start 方法
		thread.start();
		System.out.println("运行结束!");
	}

}
public class MyThread extends Thread {
	@Override
	public void run() {
		super.run();
		System.out.println("MyThread");
	}
}
public class Run {

	public static void main(String[] args) {
		MyThread mythread = new MyThread();
		mythread.start();
		System.out.println("运行结束!");
	}

}
Thread() 
          分配新的 Thread 对象。 
Thread(Runnable target) 
          分配新的 Thread 对象。 
Thread(Runnable target, String name) //
                MyThread run = new MyThread();
		Thread t1 = new Thread(run);
		Thread t2 = new Thread(run);
		Thread t3 = new Thread(run);
		Thread t4 = new Thread(run);
		Thread t5 = new Thread(run);
          分配新的 Thread 对象。 
Thread(String name) 
          分配新的 Thread 对象。    //MyThread mythread = new MyThread("1");
                                   //MyThread mythread = new MyThread("2");
                                   //MyThread mythread = new MyThread("3"); 这些都是相当于分配新的                                     对象
Thread(ThreadGroup group, Runnable target) 
          分配新的 Thread 对象。 
Thread(ThreadGroup group, Runnable target, String name) 
          分配新的 Thread 对象,以便将 target 作为其运行对象,将指定的 name 作为其名称,并作为 group 所引用的线程组的一员。 
Thread(ThreadGroup group, Runnable target, String name, long stackSize) 
          分配新的 Thread 对象,以便将 target 作为其运行对象,将指定的 name 作为其名称,作为 group 所引用的线程组的一员,并具有指定的堆栈大小。 
Thread(ThreadGroup group, String name) 
          分配新的 Thread 对象。 

线程isAlive  方法

public class MyThread extends Thread {
	@Override
	public void run() {
		System.out.println("run=" + this.isAlive());//run=true
	}
}
public class Run {
	public static void main(String[] args) {
		MyThread mythread = new MyThread();
		System.out.println("begin ==" + mythread.isAlive());//begin ==false
		mythread.start();
		System.out.println("end ==" + mythread.isAlive());//end ==true
	}
}

this与Thread.currentThread() 的区别

在自定义线程类时,如果线程类是继承java.lang.Thread的话,那么线程类就可以使用this关键字去调用继承自父类Thread的方法,this就是当前的对象。

另一方面,Thread.currentThread()可以获取当前线程的引用,一般都是在没有线程对象又需要获得线程信息时通过Thread.currentThread()获取当前代码段所在线程的引用。

尽管this与Thread.currentThread() 都可以获取到Thread的引用,但是在某种情况下获取到的引用是有差别的,下面进行举例说明

 public class MyThread extends Thread {      
 public MyThread(){
 //-------------------------Thread.currentThread()------------------
 System.out.println("Thread.currentThread().getName() = " + Thread.currentThread().getName()); 
 System.out.println("Thread.currentThread().isAlive() = " + Thread.currentThread().isAlive()); 

 //-------------------------this------------------------------------
 System.out.println("this.getName() = " + this.getName()); 
 System.out.println("this.isAlive() = " + this.isAlive()); 
} 

 

测试类:

public class Test { 
    public static void main(String[] args){               
        MyThread myThread = new MyThread(); 
        myThread.setName("A"); 
        myThread.start();             
    } 
} 

测试结果:

----------thread.currentThread()-------
Thread.currentThread().getName() = main
Thread.currentThread().isAlive() = true

----------------this ------------------
this.getName() = Thread-0
this.isAlive() = false

--------thread.currentThread()-------
Thread.currentThread().getName() = A
Thread.currentThread().isAlive() = true

----------------this ------------------
this.getName() = A
this.isAlive() = true
Thread.currentThread() == this : true

我们会发现this 与 Thread.currentThread()是同一个引用,先说构造方法中的代码结果,Thread.currentThread().getName() = main,Thread.currentThread().isAlive() = true这个结果没什么好说的,实例化MyThread,调用MyThread构造方法是主线程main,this.getName() = Thread-0,this.isAlive() = false
现在,这个this是什么?MyThread的引用,是个线程类,但是这个线程类并没有设置名字,所以Thread默认给了一个Thread-0,默认名字的规则定义如下:因为仅仅是运行构造方法,还未运行线程,所以this.isAlive() = false,之后是run()中的代码结果Thread.currentThread().getName() = A,Thread.currentThread().isAlive() = true,当前线程名字为A,A是我们手动赋予的myThread.setName("A");,并且它是运行着的,this.getName() = A,this.isAlive() = true,因为,我们运行的线程就是MyThread的引用,而this也是MyThread的引用,所以打印结果,Thread.currentThread()相同,并且Thread.currentThread() == this : true

当我们保持线程类不变,如下修改测试类:

 public class Test { 
        public static void main(String[] args){               
            MyThread myThread = new MyThread(); 
            // 将线程对象以构造参数的方式传递给Thread对象进行start()启动线程 
            Thread newThread = new Thread(myThread); 
            newThread.setName("A"); 
            newThread.start();             
        } 
    } 

测试结果如下:

Thread.currentThread().getName() = main
Thread.currentThread().isAlive() = true
this.getName() = Thread-0
this.isAlive() = false
Thread.currentThread().getName() = A
Thread.currentThread().isAlive() = true
this.getName() = Thread-0
this.isAlive() = false
Thread.currentThread() == this : false

会发现,我们会发现this 与 Thread.currentThread()不是同一个引用

将线程对象以构造参数的方式传递给Thread对象进行start()启动线程,我们直接启动的线程实际是newThread,而作为构造参数的myThread,赋给Thread类中的属性target,之后在Thread的run方法中调用target.run();

此时Thread.currentThread()是Thread的引用newThread, 而this依旧是MyThread的引用,所以是不一样的,打印的内容也不一样

线程的优先级继承性

public class MyThread2 extends Thread {
	@Override
	public void run() {
		System.out.println("MyThread2 run priority=" + this.getPriority());
	}
}
public class MyThread1 extends Thread {
	@Override
	public void run() {
		System.out.println("MyThread1 run priority=" + this.getPriority());
		MyThread2 thread2 = new MyThread2();
		thread2.start();
	}
}
public class Run {
	public static void main(String[] args) {
		System.out.println("main thread begin priority="
				+ Thread.currentThread().getPriority());//main thread begin priority=5
//		Thread.currentThread().setPriority(6);//给线程设置优先级
		System.out.println("main thread end   priority="
				+ Thread.currentThread().getPriority());//main thread end   priority=6
		MyThread1 thread1 = new MyThread1();
		thread1.start();
	}
}

结果

main thread begin priority=5
main thread end   priority=5
MyThread1 run priority=5
MyThread2 run priority=5

把上一个注释放开

public class Run {
	public static void main(String[] args) {
		System.out.println("main thread begin priority="
				+ Thread.currentThread().getPriority());//main thread begin priority=5
	        Thread.currentThread().setPriority(6);//给线程设置优先级
		System.out.println("main thread end   priority="
				+ Thread.currentThread().getPriority());//main thread end   priority=6
		MyThread1 thread1 = new MyThread1();
		thread1.start();
	}
}

结果为

main thread begin priority=5
main thread end   priority=6
MyThread1 run priority=6
MyThread2 run priority=6

优先级具有规则性

public class MyThread2 extends Thread {
	@Override
	public void run() {
		long beginTime = System.currentTimeMillis();
		long addResult = 0;
		for (int j = 0; j < 10; j++) {
			for (int i = 0; i < 50000; i++) {
				Random random = new Random();
				random.nextInt();
				addResult = addResult + i;
			}
		}
		long endTime = System.currentTimeMillis();
		System.out.println("☆☆☆☆☆thread 2 use time=" + (endTime - beginTime));
	}
}
public class MyThread1 extends Thread {
	@Override
	public void run() {
		long beginTime = System.currentTimeMillis();
		long addResult = 0;
		for (int j = 0; j < 10; j++) {
			for (int i = 0; i < 50000; i++) {
				Random random = new Random();
				random.nextInt();
				addResult = addResult + i;
			}
		}
		long endTime = System.currentTimeMillis();
		System.out.println("★★★★★thread 1 use time=" + (endTime - beginTime));
	}
}
public class Run {
	public static void main(String[] args) {
		for (int i = 0; i < 5; i++) {
			MyThread1 thread1 = new MyThread1();
			thread1.setPriority(1);
			thread1.start();

			MyThread2 thread2 = new MyThread2();
			thread2.setPriority(10);
			thread2.start();
		}
	}
}

 高优先级总是先执行完,cpu总是先让给优先级高的执行完

☆☆☆☆☆thread 2 use time=209
★★★★★thread 1 use time=232
☆☆☆☆☆thread 2 use time=235
☆☆☆☆☆thread 2 use time=236
☆☆☆☆☆thread 2 use time=238
☆☆☆☆☆thread 2 use time=244
★★★★★thread 1 use time=247
★★★★★thread 1 use time=255
★★★★★thread 1 use time=274
★★★★★thread 1 use time=282

线程运行快慢测试

public class ThreadA extends Thread {

	private int count = 0;

	public int getCount() {
		return count;
	}

	@Override
	public void run() {
		while (true) {
			count++;
		}
	}

}
public class ThreadB extends Thread {

	private int count = 0;

	public int getCount() {
		return count;
	}

	@Override
	public void run() {
		while (true) {
			count++;
		}
	}

}
public class Run {

	public static void main(String[] args) {

		try {
			ThreadA a = new ThreadA();
			//public final static int NORM_PRIORITY = 5;
			a.setPriority(Thread.NORM_PRIORITY - 3);
			a.start();

			ThreadB b = new ThreadB();
			//public final static int NORM_PRIORITY = 5;
			b.setPriority(Thread.NORM_PRIORITY + 3);
			b.start();

			Thread.sleep(20000);
			a.stop();
			b.stop();

			System.out.println("a=" + a.getCount());
			System.out.println("b=" + b.getCount());
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

	}

}

结果 

优先级高的运行的快

a=663977053
b=734505548

猜你喜欢

转载自blog.csdn.net/qq_20610631/article/details/81452282
今日推荐