线程实现方式extends Thread 和 implements Runnable

  • 线程安全:当多个线程访问同一个类时,这个类始终表现出正确的行为
  • synchronized :可在任意方法或对象上加锁

  一.extends Thread

package com.zan;

public class TestThread extends Thread{

    private int count = 5 ;
	
	//synchronized加锁 ,实现线程同步
    //加锁的这段代码称为:互斥区或临界区
	public void run(){  //也可在直接方法上加synchronized 
		synchronized (this) {			
			count--;
			System.out.println("线程"+currentThread().getName() + " count--> "+ count);
		}
	}
	
	public static void main(String[] args) {
		/**
		 *     当多个线程访问TestThread的run方法时,以排队的方式进行处理(这里排对是按照CPU分配的先后顺序而定的),
		 * 		一个线程想要执行synchronized修饰的方法里的代码:
		 * 		1 首先要获得锁
		 * 		2 若是拿到锁,执行synchronized代码体内容;拿不到锁,这个线程就会不断的尝试获得这把锁,直到拿到为止,
		 * 		   而且是多个线程同时去竞争这把锁。(也就是会有锁竞争的问题)
		 */
		TestThread thread = new TestThread();
		Thread t1 = new Thread(thread,"t1");
		Thread t2 = new Thread(thread,"t2");
		Thread t3 = new Thread(thread,"t3");
		Thread t4 = new Thread(thread,"t4");
		Thread t5 = new Thread(thread,"t5");
		t1.start();
		t2.start();
		t3.start();
		t4.start();
		t5.start();
	
	}
}

二.implements Runnable

package com.zan;

public class TestThread2 implements Runnable{

	private int count = 5 ;
	@Override
	public synchronized void run() {
		count--;
		System.out.println("线程"+Thread.currentThread().getName() + " count--> "+ count);
	}
	
	public static void main(String[] args) {
		
		TestThread2 thread = new TestThread2();
		Thread t1 = new Thread(thread,"t1");
		Thread t2 = new Thread(thread,"t2");
		Thread t3 = new Thread(thread,"t3");
		Thread t4 = new Thread(thread,"t4");
		Thread t5 = new Thread(thread,"t5");
		t1.start();
		t2.start();
		t3.start();
		t4.start();
		t5.start();
	
	}

}

Runnable比Thread好:1.适合资源共享  2.java只能单继承,但可以实现多个接口。避免继承的局限

   

猜你喜欢

转载自gwzan.iteye.com/blog/2430287