Java多线程

一、扩展java.lang.Thread类

public class ThreadDemo1 {
     public static void main(String[] args){
         Demo d = new Demo();
         d.start();
         for(int i=0;i<60;i++){
             System.out.println(Thread.currentThread().getName()+i);
         }

     }
 }
 class Demo extends Thread{
     public void run(){
         for(int i=0;i<60;i++){
             System.out.println(Thread.currentThread().getName()+i);
         }
     }
 }

二、实现java.lang.Runnable接口

public class ThreadDemo2 {
    public static void main(String[] args){
        Demo2 d =new Demo2();
        Thread t = new Thread(d);
        t.start();
        for(int x=0;x<60;x++){
            System.out.println(Thread.currentThread().getName()+x);
        }
    }
}
class Demo2 implements Runnable{
    public void run(){
        for(int x=0;x<60;x++){
            System.out.println(Thread.currentThread().getName()+x);
        }
    }
}

三、Thread和Runnable的区别

如果一个类继承Thread,则不适合资源共享。但是如果实现了Runable接口的话,则很容易的实现资源共享。

总结:

实现Runnable接口比继承Thread类所具有的优势:

1):适合多个相同的程序代码的线程去处理同一个资源

2):可以避免java中的单继承的限制

3):增加程序的健壮性,代码可以被多个线程共享,代码和数据独立

java中,每次程序运行至少启动2个线程。一个是main线程,一个是垃圾收集线程。因为每当使用java命令执行一个类的时候,实际上都会启动 一个JVM,每一个jVM实习在就是在操作系统中启动了一个进程。

四、线程状态转换

1、新建状态(New):新创建了一个线程对象。
2、就绪状态(Runnable):线程对象创建后,其他线程调用了该对象的start()方法。该状态的线程位于可运行线程池中,变得可运行,等待获取CPU的使用权。
3、运行状态(Running):就绪状态的线程获取了CPU,执行程序代码。
4、阻塞状态(Blocked):阻塞状态是线程因为某种原因放弃CPU使用权,暂时停止运行。直到线程进入就绪状态,才有机会转到运行状态。阻塞的情况分三种:
(一)、等待阻塞:运行的线程执行wait()方法,JVM会把该线程放入等待池中。
(二)、同步阻塞:运行的线程在获取对象的同步锁时,若该同步锁被别的线程占用,则JVM会把该线程放入锁池中。
(三)、其他阻塞:运行的线程执行sleep()或join()方法,或者发出了I/O请求时,JVM会把该线程置为阻塞状态。当sleep()状态超时、join()等待线程终止或者超时、或者I/O处理完毕时,线程重新转入就绪状态。
5、死亡状态(Dead):线程执行完了或者因异常退出了run()方法,该线程结束生命周期。

线程的调度

1、调整线程优先级:Java线程有优先级,优先级高的线程会获得较多的运行机会。
 
Java线程的优先级用整数表示,取值范围是1~10,Thread类有以下三个静态常量:
static int MAX_PRIORITY
          线程可以具有的最高优先级,取值为10。
static int MIN_PRIORITY
          线程可以具有的最低优先级,取值为1。
static int NORM_PRIORITY
          分配给线程的默认优先级,取值为5。
 
Thread类的setPriority()和getPriority()方法分别用来设置和获取线程的优先级。
 
每个线程都有默认的优先级。主线程的默认优先级为Thread.NORM_PRIORITY。
线程的优先级有继承关系,比如A线程中创建了B线程,那么B将和A具有相同的优先级。
JVM提供了10个线程优先级,但与常见的操作系统都不能很好的映射。如果希望程序能移植到各个操作系统中,应该仅仅使用Thread类有以下三个静态常量作为优先级,这样能保证同样的优先级采用了同样的调度方式。
 
2、线程睡眠:Thread.sleep(long millis)方法,使线程转到阻塞状态。millis参数设定睡眠的时间,以毫秒为单位。当睡眠结束后,就转为就绪(Runnable)状态。sleep()平台移植性好。
 
3、线程等待:Object类中的wait()方法,导致当前的线程等待,直到其他线程调用此对象的 notify() 方法或 notifyAll() 唤醒方法。这个两个唤醒方法也是Object类中的方法,行为等价于调用 wait(0) 一样。
 
4、线程让步:Thread.yield() 方法,暂停当前正在执行的线程对象,把执行机会让给相同或者更高优先级的线程。
 
5、线程加入:join()方法,等待其他线程终止。在当前线程中调用另一个线程的join()方法,则当前线程转入阻塞状态,直到另一个进程运行结束,当前线程再由阻塞转为就绪状态。
 
6、线程唤醒:Object类中的notify()方法,唤醒在此对象监视器上等待的单个线程。如果所有线程都在此对象上等待,则会选择唤醒其中一个线程。选择是任意性的,并在对实现做出决定时发生。线程通过调用其中一个 wait 方法,在对象的监视器上等待。 直到当前的线程放弃此对象上的锁定,才能继续执行被唤醒的线程。被唤醒的线程将以常规方式与在该对象上主动同步的其他所有线程进行竞争;例如,唤醒的线程在作为锁定此对象的下一个线程方面没有可靠的特权或劣势。类似的方法还有一个notifyAll(),唤醒在此对象监视器上等待的所有线程。

线程类的一些常用方法: 

  sleep(): 强迫一个线程睡眠N毫秒。 
  isAlive(): 判断一个线程是否存活。 
  join(): 等待线程终止。 
  activeCount(): 程序中活跃的线程数。 
  enumerate(): 枚举程序中的线程。 
    currentThread(): 得到当前线程。 
  isDaemon(): 一个线程是否为守护线程。 
  setDaemon(): 设置一个线程为守护线程。(用户线程和守护线程的区别在于,是否等待主线程依赖于主线程结束而结束) 
  setName(): 为线程设置一个名称。 
  wait(): 强迫一个线程等待。 
  notify(): 通知一个线程继续运行。 
  setPriority(): 设置一个线程的优先级。


五、线程同步

1.  把synchronized当作函数修饰符时,示例代码如下:

Public synchronized void methodAAA()

{

//….

}

2.同步块,示例代码如下:

            public void method3(SomeObject so)

              {

                     synchronized(so)

}


      
      
1、线程同步的目的是为了保护多个线程反问一个资源时对资源的破坏。
2、线程同步方法是通过锁来实现,每个对象都有切仅有一个锁,这个锁与一个特定的对象关联,线程一旦获取了对象锁,其他访问该对象的线程就无法再访问该对象的其他非同步方法。
3、对于静态同步方法,锁是针对这个类的,锁对象是该类的Class对象。静态和非静态方法的锁互不干预。一个线程获得锁,当在一个同步方法中访问另外对象上的同步方法时,会获取这两个对象锁。
4、对于同步,要时刻清醒在哪个对象上同步,这是关键。
5、编写线程安全的类,需要时刻注意对多个线程竞争访问资源的逻辑和安全做出正确的判断,对“原子”操作做出分析,并保证原子操作期间别的线程无法访问竞争资源。
6、当多个线程等待一个对象锁时,没有获取到锁的线程将发生阻塞。
7、死锁是线程间相互等待锁锁造成的,在实际中发生的概率非常的小。真让你写个死锁程序,不一定好使,呵呵。但是,一旦程序发生死锁,程序将死掉。

六、线程经典实例

1.生产消费
<span style="font-size:12px;color:#000099;">package www.Thread.study;
/*
class Resourse11{
	private String name;
	private int count=1;
	private boolean flag=false;
	public synchronized void set(String name){
		while(flag)
			try {
				wait();
			} catch (InterruptedException e){}
		this.name=name+count;
		count++;
		System.out.println(Thread.currentThread().getName()+"..生产者.."+this.name);
		notifyAll();
		flag=true;
	}
	public synchronized void out(){
		while(!flag)
			try {
				wait();
			} catch (InterruptedException e){}
		System.out.println(Thread.currentThread().getName()+"..消费者......"+this.name);		
		notifyAll();
		flag=false;	
	}
}
class Producer implements Runnable{
	Resourse11 r;
	Producer(Resourse11 r){
		this.r=r;		
	}
	public void run(){
		int i=0;
		while(true){			
			r.set("烤鸭");
		}		
	}	
}
class Coustomer implements Runnable{
	Resourse11 r;
	Coustomer(Resourse11 r){
		this.r=r;
	}
	public void run(){
		while(true){			
			r.out();						
		}		
	}
}
public class ProducerCoustomer {
	public static void main(String[] args){
		//创建资源
		Resourse11 r=new Resourse11();
		//创建任务
		Producer t1=new Producer(r);		
		Coustomer t2=new Coustomer(r);		
		//创建线程,执行路径
		Thread a1=new Thread(t1);
		Thread a2=new Thread(t2);
		Thread a3=new Thread(t1);
		Thread a4=new Thread(t1);
		//开启线程
		a1.start();
		a2.start();
		a3.start();
		a4.start();
		
	}

}
 */
import java.util.concurrent.locks.*;

class Resourse11 {
	private String name;
	private int count = 1;
	private boolean flag = false;
	// 创建一个锁对象
	Lock lock = new ReentrantLock();
	// 通过已有锁获取该锁上的监视器对象
	//Condition con = lock.newCondition();
	Condition Producer_con = lock.newCondition();
	Condition Customer_con = lock.newCondition();
	public void set(String name) {
		lock.lock();
		try {
			while (flag)
				try {
					Producer_con.await();
				} catch (InterruptedException e) {
				}
			this.name = name + count;
			count++;
			System.out.println(Thread.currentThread().getName() + "..生产者.."
					+ this.name);
			Customer_con.signalAll();
			flag = true;
		} finally {
			lock.unlock();
		}

	}

	public void out() {
		lock.lock();
		try {
			while (!flag)
				try {
					Customer_con.await();
				} catch (InterruptedException e) {
				}
			System.out.println(Thread.currentThread().getName() + "..消费者......"+ this.name);
			Producer_con.signalAll();
			flag = false;
		} 
		finally {
			lock.unlock();
		}

	}
}

class Producer implements Runnable {
	Resourse11 r;

	Producer(Resourse11 r) {
		this.r = r;
	}

	public void run() {
		int i = 0;
		while (true) {
			r.set("烤鸭");
		}
	}
}  

class Coustomer implements Runnable {
	Resourse11 r;

	Coustomer(Resourse11 r) {
		this.r = r;
	}

	public void run() {
		while (true) {
			r.out();
		}
	}
}

public class ProducerCoustomer {
	public static void main(String[] args) {
		// 创建资源
		Resourse11 r = new Resourse11();
		// 创建任务
		Producer t1 = new Producer(r);
		Coustomer t2 = new Coustomer(r);
		// 创建线程,执行路径
		Thread a1 = new Thread(t1);
		Thread a2 = new Thread(t2);
		Thread a3 = new Thread(t1);
		Thread a4 = new Thread(t1);
		// 开启线程
		a1.start();
		a2.start();
		a3.start();
		a4.start();

	}

}</span>


2.等待唤醒
package www.Thread.study;

/*
 等待|唤醒机制
 涉及的方式
 
 1.wait():让线程处于冻结状态。被wait的线程会被存储到线程池中
 2.notify();唤醒线程池中一个线程(任意)
 3.notifyAll();唤醒线程池中所有线程
 
 
 */
class Resourse{
	String name;
	String sex;
	
}
class Input implements Runnable{
	Resourse r;
	Input(Resourse r){
		this.r=r;		
	}
	public void run(){
		int i=0;
		while(true){
			synchronized(r){												
				if(i==0){
					r.name="xiaoli";
					r.sex="nan";
				}else{
					r.name="芊芊";
					r.sex="女女女";
				}
								
			}
			i=(i+1)%2;
		}
	}	
}
class Output implements Runnable{
	Resourse r;
	Output(Resourse r){
		this.r=r;
	}
	public void run(){
		while(true){
			synchronized(r){				
				System.out.println(r.name+"..."+r.sex);				
			}			
		}		
	}
}
public class Tongxin{
	public static void main(String[] args){
		//创建资源
		Resourse r=new Resourse();
		//创建任务
		Input t1=new Input(r);
		Output t2=new Output(r);
		//创建线程,执行路径
		Thread a1=new Thread(t1);
		Thread a2=new Thread(t2);
		//开启线程
		a1.start();
		a2.start();
		
	}

}

//代码优化 详细看Dengdaihuanxing.java
-----------------------------------------------------
package www.Thread.study;
/*
 等待|唤醒机制
 涉及的方式
 
 1.wait():让线程处于冻结态状。被atiw的线程会被存储到线程池中
 2.notify();唤醒线程池中一个线程(任意)
 3.notifyAll();唤醒线程池中所有线程
 
 */






class Resourse2{
<span style="white-space:pre">	</span>String name;
<span style="white-space:pre">	</span>String sex;
<span style="white-space:pre">	</span>boolean flag=false;
}
class Input2 implements Runnable{
<span style="white-space:pre">	</span>Resourse2 r;
<span style="white-space:pre">	</span>Input2(Resourse2 r){
<span style="white-space:pre">		</span>this.r=r;<span style="white-space:pre">		</span>
<span style="white-space:pre">	</span>}
<span style="white-space:pre">	</span>public void run(){
<span style="white-space:pre">		</span>int i=0;
<span style="white-space:pre">		</span>while(true){
<span style="white-space:pre">			</span>synchronized(r){
<span style="white-space:pre">				</span>if(r.flag)
<span style="white-space:pre">					</span>try {
<span style="white-space:pre">						</span>r.wait();
<span style="white-space:pre">					</span>} catch (InterruptedException e){}
<span style="white-space:pre">				</span>if(i==0){
<span style="white-space:pre">					</span>r.name="xiaoli";
<span style="white-space:pre">					</span>r.sex="nan";
<span style="white-space:pre">				</span>}else{
<span style="white-space:pre">					</span>r.name="芊芊";
<span style="white-space:pre">					</span>r.sex="女女女";
<span style="white-space:pre">				</span>}
<span style="white-space:pre">				</span>r.notify();
<span style="white-space:pre">				</span>r.flag=true;
<span style="white-space:pre">			</span>}
<span style="white-space:pre">			</span>i=(i+1)%2;
<span style="white-space:pre">		</span>}
<span style="white-space:pre">	</span>}<span style="white-space:pre">	</span>
}
class Output2 implements Runnable{
<span style="white-space:pre">	</span>Resourse2 r;
<span style="white-space:pre">	</span>Output2(Resourse2 r){
<span style="white-space:pre">		</span>this.r=r;
<span style="white-space:pre">	</span>}
<span style="white-space:pre">	</span>public void run(){
<span style="white-space:pre">		</span>while(true){
<span style="white-space:pre">			</span>synchronized(r){
<span style="white-space:pre">				</span>if(!r.flag)
<span style="white-space:pre">					</span>try {
<span style="white-space:pre">						</span>r.wait();
<span style="white-space:pre">					</span>} catch (InterruptedException e) {}
<span style="white-space:pre">				</span>System.out.println(r.name+"..."+r.sex);<span style="white-space:pre">		</span>
<span style="white-space:pre">				</span>r.notify();
<span style="white-space:pre">				</span>r.flag=false;
<span style="white-space:pre">			</span>}<span style="white-space:pre">			</span>
<span style="white-space:pre">		</span>}<span style="white-space:pre">		</span>
<span style="white-space:pre">	</span>}
}
public class Dengdaihuanxing{
<span style="white-space:pre">	</span>public static void main(String[] args){
<span style="white-space:pre">		</span>//创建资源
<span style="white-space:pre">		</span>Resourse2 r=new Resourse2();
<span style="white-space:pre">		</span>//创建任务
<span style="white-space:pre">		</span>Input2 t1=new Input2(r);
<span style="white-space:pre">		</span>Output2 t2=new Output2(r);
<span style="white-space:pre">		</span>//创建线程,执行路径
<span style="white-space:pre">		</span>Thread a1=new Thread(t1);
<span style="white-space:pre">		</span>Thread a2=new Thread(t2);
<span style="white-space:pre">		</span>//开启线程
<span style="white-space:pre">		</span>a1.start();
<span style="white-space:pre">		</span>a2.start();
<span style="white-space:pre">		</span>
<span style="white-space:pre">	</span>}


}






/*
//代码优化
class Resourse1{
<span style="white-space:pre">	</span>private String name;
<span style="white-space:pre">	</span>private String sex;
<span style="white-space:pre">	</span>private boolean flag=false;
<span style="white-space:pre">	</span>public synchronized void set(String name,String sex){
<span style="white-space:pre">		</span>if(flag)
<span style="white-space:pre">			</span>try {
<span style="white-space:pre">				</span>wait();
<span style="white-space:pre">			</span>} catch (InterruptedException e){}
<span style="white-space:pre">		</span>this.name=name;
<span style="white-space:pre">		</span>this.sex=sex;
<span style="white-space:pre">		</span>notify();
<span style="white-space:pre">		</span>flag=true;
<span style="white-space:pre">	</span>}
<span style="white-space:pre">	</span>public synchronized void out(){
<span style="white-space:pre">		</span>if(!flag)
<span style="white-space:pre">			</span>try {
<span style="white-space:pre">				</span>wait();
<span style="white-space:pre">			</span>} catch (InterruptedException e){}
<span style="white-space:pre">		</span>System.out.println(name+"..+.."+sex);<span style="white-space:pre">		</span>
<span style="white-space:pre">		</span>notify();
<span style="white-space:pre">		</span>flag=false;<span style="white-space:pre">	</span>
<span style="white-space:pre">	</span>}
}
class Input1 implements Runnable{
<span style="white-space:pre">	</span>Resourse1 r;
<span style="white-space:pre">	</span>Input1(Resourse1 r){
<span style="white-space:pre">		</span>this.r=r;<span style="white-space:pre">		</span>
<span style="white-space:pre">	</span>}
<span style="white-space:pre">	</span>public void run(){
<span style="white-space:pre">		</span>int i=0;
<span style="white-space:pre">		</span>while(true){<span style="white-space:pre">			</span>
<span style="white-space:pre">			</span>if(i==0){
<span style="white-space:pre">				</span>r.set("xiaoming","man");
<span style="white-space:pre">			</span>}else{
<span style="white-space:pre">				</span>r.set("芊芊", "女女女");<span style="white-space:pre">	</span>
<span style="white-space:pre">			</span>}<span style="white-space:pre">	</span>
<span style="white-space:pre">			</span>i=(i+1)%2;
<span style="white-space:pre">		</span>}
<span style="white-space:pre">		</span>
<span style="white-space:pre">	</span>}<span style="white-space:pre">	</span>
}
class Output1 implements Runnable{
<span style="white-space:pre">	</span>Resourse1 r;
<span style="white-space:pre">	</span>Output1(Resourse1 r){
<span style="white-space:pre">		</span>this.r=r;
<span style="white-space:pre">	</span>}
<span style="white-space:pre">	</span>public void run(){
<span style="white-space:pre">		</span>while(true){<span style="white-space:pre">			</span>
<span style="white-space:pre">			</span>r.out();<span style="white-space:pre">						</span>
<span style="white-space:pre">		</span>}<span style="white-space:pre">		</span>
<span style="white-space:pre">	</span>}
}
public class Dengdaihuanxing{
<span style="white-space:pre">	</span>public static void main(String[] args){
<span style="white-space:pre">		</span>//创建资源
<span style="white-space:pre">		</span>Resourse1 r=new Resourse1();
<span style="white-space:pre">		</span>//创建任务
<span style="white-space:pre">		</span>Input1 t1=new Input1(r);
<span style="white-space:pre">		</span>Output1 t2=new Output1(r);
<span style="white-space:pre">		</span>//创建线程,执行路径
<span style="white-space:pre">		</span>Thread a1=new Thread(t1);
<span style="white-space:pre">		</span>Thread a2=new Thread(t2);
<span style="white-space:pre">		</span>//开启线程
<span style="white-space:pre">		</span>a1.start();
<span style="white-space:pre">		</span>a2.start();<span style="white-space:pre">		</span>
<span style="white-space:pre">	</span>}
}
*/



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值