黑马程序员---回顾之java多线程技术

------- android培训、java培训、期待与您交流! ----------

1.多线程概述:

进程:正在进行中的程序(直译)。 
线程:就是进程中一个负责程序执行的控制单元(执行路径), 一个进程中可以多执行路径,称之为多线程。 一个进程中至少要有一个线程。 
开启多个线程是为了同时运行多部分代码。 每一个线程都有自己运行的内容。这个内容可以称为线程要执行的任务。 

多线程好处:解决了多部分同时运行的问题。 

多线程的弊端:线程太多回到效率的降低。 

其实应用程序的执行都是cpu在做着快速的切换完成的,这个切换是随机的。 JVM启动时就启动了多个线程,至少有两个线程可以分析的出来。 1,执行main函数的线程, 
该线程的任务代码都定义在main函数中。  2,负责垃圾回收的线程。

2.线程创建方法:

创建线程方式一:继承Thread类。  
步骤: 
1,定义一个类继承Thread类。 2,覆盖Thread类中的run方法。 
3,直接创建Thread的子类对象创建线程。 
4,调用start方法开启线程并调用线程的任务run方法执行。  
可以通过Thread的getName获取线程的名称 Thread-编号(从0开始)  
主线程的名字就是main。

class Demo extends Thread { 
 private String name;  
 Demo(String name)  { 
  super(name); 
  //this.name = name;  } 
 public void run()  { 
  for(int x=0; x<10; x++)   { 
 System.out.println(name+"....x="+x+".....name="+Thread.currentThread().getName());   
  }  
 } 
} 
class ThreadDemo2  {   
	public static void main(String[] args)   {  
	Demo d1 = new Demo("旺财"); 
  
	Demo d2 = new Demo("xiaoqiang"); 
  
	d1.start();//开启线程,调用run方法。    
  
	d2.start(); 
  
	System.out.println("over...."+Thread.currentThread().getName()); 
 
	} 

} 

创建线程的第二种方式:实现Runnable接口

步骤: 
1,定义类实现Runnable接口。 
2,覆盖接口中的run方法,将线程的任务代码封装到run方法中。 
3,通过Thread类创建线程对象,并将Runnable接口的子类对象作为Thread类的构造函数的参数进行传递。  为什么?因为线程的任务都封装在Runnable接口子类对象的run方法中。  所以要在线程对象创建时就必须明确要运行的任务。 4,调用线程对象的start方法开启线程。  
实现Runnable接口的好处: 
1,将线程的任务从线程的子类中分离出来,进行了单独的封装。  按照面向对象的思想将任务的封装成对象。 2,避免了java单继承的局限性。 
所以,创建线程的第二种方式较为常用。

class Demo implements Runnable{
 public void run()  { 
  show(); 
 } 
 public void show()  { 
  for(int x=0; x<20; x++)   { 
   System.out.println(Thread.currentThread().getName()+"....."+x); 
 		}  
	}
}  
class  ThreadDemo { 
 public static void main(String[] args)   {  
   Demo d = new Demo(); 
  Thread t1 = new Thread(d);   
  Thread t2 = new Thread(d);   
  t1.start();   
  t2.start();  
	}
}

3.线程安全问题

线程安全问题产生的原因: 
1,多个线程在操作共享的数据。 
2,操作共享数据的线程代码有多条。 
当一个线程在执行操作共享数据的多条代码过程中,其他线程参与了运算。 就会导致线程安全问题的产生。   
解决思路; 
就是将多条操作共享数据的线程代码封装起来,当有线程在执行这些代码的时候, 其他线程时不可以参与运算的。 
必须要当前线程把这些代码都执行完毕后,其他线程才可以参与运算。  在java中,利用同步代码块或同步方法,jdk5.0的lock就可以解决此类问题。  
同步代码块的格式: 
synchronized(对象) { 
 需要被同步的代码 ;
 } 
同步的好处:解决了线程的安全问题。 
同步的弊端:相对降低了效率,因为同步外的线程的都会判断同步锁。 同步的前提:同步中必须有多个线程并使用同一个锁。

静态的同步函数使用的锁是该函数所属字节码文件对象, 

可以用 getClass方法获取,也可以用当前类名.class 表示。

同步函数的使用的锁是this; 

同步函数和同步代码块的区别:

同步函数的锁是固定的this, 同步代码块的锁是任意的对象。 建议使用同步代码块。

案例:

多线程典型案例之银行存钱

/*
 *   需求:储户,两个,每个都到银行存钱每次存100,,共存三次。 
 */  
class Bank { 
 private int sum; 
//  private Object obj = new Object();  
// 同步函数  
public synchronized void add(int num){ 
	 sum = sum + num;  
  	 try{Thread.sleep(10);}catch(InterruptedException e){}   
	 System.out.println("sum="+sum); 
	 } 
}  
class Cus implements Runnable { 
 private Bank b = new Bank();  
 public void run()  { 
  for(int x=0; x<3; x++)   { 
   b.add(100);   
		} 
	 } 
}  
class BankDemo  { 
 public static void main(String[] args)   { 
  Cus c = new Cus(); 
  Thread t1 = new Thread(c);   
	Thread t2 = new Thread(c);  
	 t1.start();   
	t2.start();  
	} 
}

4.死锁

产生情况:同步里面还有同步而且用的不同的锁

典型死锁案例之同步代码块嵌套

package cn.djb.thread;

public class DeadLockTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		A a1=new A(false);
		A a2=new A(true);

		Thread t1=new Thread(a1);
		Thread t2=new Thread(a2);
	
		
		t1.start();
		
		t2.start();
	
	}

}
class A implements Runnable{
	private boolean flag;
	public A(boolean b){
		this.flag=b;
	}
	public void run() {
		if(flag){
		synchronized (Lock.locka) {
	
			System.out.println("if locka");
			synchronized (Lock.lockb) {
				System.out.println("if lockb");
			}
			}
		}
		else{
			synchronized (Lock.lockb) {
				System.out.println("else lockb");
				synchronized (Lock.locka) {
					System.out.println("else locka");
				}
				}
		}
		}
		
		
	}


class Lock{
	public static Object locka=new Object();
	public static Object lockb=new Object();
}

5.多线程下的单例(懒汉式)

package cn.djb.single;

public class Single {
	private Single(){};
	private static Single s=null;
	public static Single getSingle(){
		if(s==null){
			synchronized (Single.class) {
				if(s==null){
					s=new Single();
					return s;
				}
				return s;
			}
			}
		return s;
	}
}

6.线程等待唤醒机制:

线程状态图:


wait() 释放执行资格,线程处于等待状态

notify() 唤醒对方第一个处于等待状态的线程

notifyAll() 唤醒对方所有处于等待状态的线程

案例:

package cn.djb.thread;
/*
 * 要求:给一个对象设置一个人名和性别,然后才可以取走,取走后才可以再设置,如此交替
 */
public class WaitNotifyTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Res r = new Res();
		Input in = new Input(r);
		Output out = new Output(r);
		Thread t1 = new Thread(in);
		Thread t2 = new Thread(out);
		t1.start();
		t2.start();

	}

}

class Res {
	private String name;
	private String sex;
	private boolean s;

	public boolean isS() {
		return s;
	}

	public void setS(boolean s) {
		this.s = s;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

}

class Input implements Runnable {
	private Res r;
	private boolean b;

	public Input(Res r) {
		this.r = r;
	}

	public void run() {
		for (int i = 0; i < 1000; i++) {
			synchronized (r) {
				if (r.isS())
					try {
						r.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				if (b) {
					r.setName("张三");
					r.setSex("男");
					this.b = false;
				} else {
					r.setName("lili");
					r.setSex("female");
					this.b = true;
				}
				r.setS(true);
				r.notify();
			}
		}

	}

}

class Output implements Runnable {
	private int num;
	private Res r;

	public Output(Res r) {
		this.r = r;
	}

	public void run() {
		for (int i = 0; i < 1000; i++) {
			synchronized (r) {
				if (r.isS()) {
					System.out.println(r.getName() + "=" + r.getSex());
					num++;
					r.setS(false);
					r.notify();
				} else {
					try {
						r.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}

			}
			if (i == 999)
				System.out.println(num);
		}

	}

}

多生产者与多消费者案例:

class ProducerConsumerDemo 
{
	public static void main(String[] args) 
	{
		Resource r = new Resource();

		Producer pro = new Producer(r);
		Consumer con = new Consumer(r);

		Thread t1 = new Thread(pro);
		Thread t2 = new Thread(pro);
		Thread t3 = new Thread(con);
		Thread t4 = new Thread(con);

		t1.start();
		t2.start();
		t3.start();
		t4.start();

	}
}

/*
对于多个生产者和消费者。
为什么要定义while判断标记。
原因:让被唤醒的线程再一次判断标记。


为什么定义notifyAll,
因为需要唤醒对方线程。
因为只用notify,容易出现只唤醒本方线程的情况。导致程序中的所有线程都等待。

*/


class Resource
{
	private String name;
	private int count = 1;
	private boolean flag = false;
			//  t1    t2
	public synchronized void set(String name)
	{
		while(flag)
			try{this.wait();}catch(Exception e){}//t1(放弃资格)  t2(获取资格)
		this.name = name+"--"+count++;

		System.out.println(Thread.currentThread().getName()+"...生产者.."+this.name);
		flag = true;
		this.notifyAll();
	}


	//  t3   t4  
	public synchronized void out()
	{
		while(!flag)
			try{wait();}catch(Exception e){}//t3(放弃资格) t4(放弃资格)
		System.out.println(Thread.currentThread().getName()+"...消费者........."+this.name);
		flag = false;
		this.notifyAll();
	}
}

class Producer implements Runnable
{
	private Resource res;

	Producer(Resource res)
	{
		this.res = res;
	}
	public void run()
	{
		while(true)
		{
			res.set("+商品+");
		}
	}
}

class Consumer implements Runnable
{
	private Resource res;

	Consumer(Resource res)
	{
		this.res = res;
	}
	public void run()
	{
		while(true)
		{
			res.out();
		}
	}
}

JDK5.0升级版多生产者与消费者lock锁:

jdk1.5以后将同步和锁封装成了对象。  并将操作锁的隐式方式定义到了该对象中, 将隐式动作变成了显示动作。  
Lock接口: 出现替代了同步代码块或者同步函数。将同步的隐式锁操作变成现实锁操作。 同时更为灵活。可以一个锁上加上多组监视器。 lock():获取锁。 
unlock():释放锁,通常需要定义finally代码块中。 
Condition接口:出现替代了Object中的wait notify notifyAll方法。    将这些监视器方法单独进行了封装,变成Condition监视器对象。    可以任意锁进行组合。

await(); signal(); signalAll();

package cn.djb.thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ThreadLockTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Resource r=new Resource();
		Productor p=new Productor(r);
		Customer c=new Customer(r);
		Thread t1=new Thread(p);
		Thread t2=new Thread(p);
		Thread t3=new Thread(c);
		Thread t4=new Thread(c);
		t1.start();
		t2.start();
		t3.start();
		t4.start();

	}
	

}

class Resource{
	private String name;
	private int  number=0;
	private boolean flag;
	private Lock lock=new ReentrantLock();
	private Condition condition_pro=lock.newCondition();
	private Condition condition_cus=lock.newCondition();
	public void sale() {
		lock.lock();
		try{
		while(!flag)
			condition_cus.await();
		System.out.println(Thread.currentThread().getName()+"............"+"sale"+name+number);
		flag=false;
		condition_pro.signal();
		}catch (Exception e) {
			
		}finally{
			lock.unlock();
		}
	}
	public void product(String name) {
		lock.lock();
		try{
		while(flag)
			condition_pro.await();
		this.name = name;
		this.number++;
		System.out.println(Thread.currentThread().getName()+"..."+"product"+this.name+this.number);
		flag=true;
		condition_cus.signal();
		}catch (Exception e) {
			
		}
		finally{
			lock.unlock();
		}
		
	}

}
class Productor implements Runnable{
	private Resource r;
	public Productor(Resource r){
		this.r=r;
	}
	public void run() {
		for(int i=0;i<600;i++)
		r.product("北京烤鸭");
	}
	
}
class Customer implements Runnable{
	private Resource r;
	public Customer(Resource r){
		this.r=r;
	}
	public void run() {
		for(int i=0;i<600;i++)
		r.sale();
	}
	
}


------- android培训、java培训、期待与您交流! ----------

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值