黑马_blog3_多线程

---------------------- <a href="http://www.itheima.com"target="blank">ASP.Net+Unity开发</a>、<a href="http://www.itheima.com"target="blank">.Net培训</a>、期待与您交流! ----------------------

1多线程(概述)

进程:是一个正在执行中的程序,每一个进程执行都有一个执行顺序,该顺序就是一个执行路径,或者叫一个控制单元。

线程就是进程中的一个独立的执行单元。

线程在控制着进程的执行。

一个进程中至少有一个线程。

Jvm启动的时候会有一个进程,java.exe,该进程中至少有一个线程负责java程序的执行,而且这个线程运行的代码存在于main方法中,该线程称之为主线程。其实更多细节说明jvm启动不知一个线程,还有垃圾回收机制的线程。

下载就是多线程的

2多线程(创建线程——继承Thread类)

如何在自定义的代码中,自定义一个线程呢?

通过对api的查找,java已经提供了对多线程这类事物的描述,就是Thread类。

创建线程的第一种方式:继承Thread

继承Thread 

复写Thread类中的run方法,将自定义的代码存储在run中,让线程运行

调用线程的start方法,该方法有2个作用:启动线程,调用run方法;

代码:

class Test 
{
	public static void main(String[] args) 
	{
		//调用线程的start方法
		new Demo().start();
		for(int i=0;i<50;i++)
		{
			System.out.println("main"+i);
		}
	}
}
//继承Thread类
class Demo extends Thread
{
	//复写run方法
	public void run()
	{
		for(int i=0;i<60;i++)
		{
			System.out.println("hello"+i);
		}
	}
}

 

发现运行结果每一次都不同:

因为多个线程都获取到CPU执行权,cpu执行到谁,谁就运行,在某一个时刻,只能有一个程序在运行(多核除外),cpu在做着快速的切换,以达到看上去同时运行的结果。我们可以形象地把多线程的运行形容为在互相抢夺cpu的执行权,这就是多线程的一个特性:随机性,谁抢到谁执行,执行多长时间cpu说的算。

3多线程(创建线程run和start特点)

为什么要覆盖run方法呢?

Thread类用于描述线程,该类定义了一个功能,用于存储线程要运行的代码,该存储功能就是run方法,也就是Thread类中的run方法,用于存储线程要运行的代码

Demo d=new Demo();

d.start();//开启线程并执行线程中的run方法;有多个线程时,交替运行

d.run();//仅仅是对象调用方法,而线程创建了,没有运行,有多个线程时,顺序执行

4多线程(线程练习)

需求:创建两个线程和主线程交替运行

代码:

class Test 
{
	public static void main(String[] args) 
	{
		new Demo("Thread--1").start();
		new Demo("Thread--2").start();
		for(int i=0;i<90;i++)
		{
			System.out.println("main\t"+i);
		}
	}
}
class Demo extends Thread
{
	private String name;
	public Demo(String name)
	{
		this.name=name;
	}
	public void run()
	{
		for(int i=0;i<60;i++)
		{
			System.out.println(name+"\t"+i);
		}
	}
}

5多线程(线程运行状态)

 

6多线程(获取线程对象以及名称)

currentThread():获取当前线程对象;

getName():获取线程名称;

setName():设置线程名称;(构造方法也可设置线程名称)

7多线程(售票的例子)

需求:简单的买票程序,同时多个窗口买票

代码:

class Demo 
{
	public static void main(String[] args) 
	{
		new Ticket().start();
		new Ticket().start();
	}
}
class Ticket extends Thread
{
	private int ticket=100;
	public void run()
	{
		while(true)
		{
			if(ticket>0)
				System.out.println(Thread.currentThread().getName()+"\t"+(ticket--));
		}
	}
}

发现上面的代码有问题:2个线程卖了200张票,不符合要求,如果改为private static int ticket=100;因为是静态变量,在类加载的时候就加载,存在的周期长,所以比较浪费资源,有什么办法呢?

8多线程(创建线程--实现Runnable接口)

上述买票的例子代码:

class Demo 
{
	public static void main(String[] args) 
	{
		Ticket t=new Ticket();
		new Thread(t).start();
		new Thread(t).start();
	}
}
 class Ticket implements Runnable
 {
	 private int ticket=100;
	 public void run()
	 {
		 while(true)
		 {
			 if(ticket>0)
				 System.out.println(Thread.currentThread().getName()+"\t"+(ticket--));
		 }
	 }
 }

上面的代码实现2个线程共卖100张票

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

步骤:

定义类实现Runnable接口

覆盖Runnable接口中的run()方法(将线程运行的代码存放在run方法中);

通过Thread类建立线程对象

Runnable接口的子类对象作为实际参数传给Thread类的构造函数

调用Thread类的start方法开启线程并调用Runnable接口子类run方法。

为什么要将Runnable接口的子类对象作为实际参数传递给Thread类的构造函数?

因为,自定义的run方法所属的对象是Runnable接口的子类对象,所以要让线程去执行指定对象的run方法,就必须明确该run()方法所属的对象。

实现方式和继承方式有什么区别?

继承Thread类:线程代码存放在Thread子类run()方法中;

实现Runnable类:线程代码存在在接口的子类的run()方法中;

实现方式的好处:避免了单继承的局限性,在定义线程时,建议使用实现方式。

9多线程(多线程的安全问题)

上面买票的例子代码:

class Demo 
{
	public static void main(String[] args) 
	{
		Ticket t=new Ticket();
		new Thread(t).start();
		new Thread(t).start();
	}
}
 class Ticket implements Runnable
 {
	 private int ticket=100;
	 public void run()
	 {
		 while(true)
		 {
			 if(ticket>0)
			 { 
				 try{
					Thread.sleep(50);
				 }catch(Exception e)
				 {
					e.printStackTrace();
				 }
				 System.out.println(Thread.currentThread().getName()+"\t"+(ticket--));
			 }
				
		 }
	 }
 }

通过分析发现,打印出了0-1-2等错票。

多线程的运行出现了安全问题。

问题的原因:当多条语句在操作同一个线程共享数据时,一个线程对多条语句只执行了一部分,还没有执行完,另一个线程参与进来执行,导致了共享数据的错误。

解决办法:对多条操作共享数据的语句,只能让一个线程都执行完,在执行的过程中,其他线程不可以参与进程。(类比上厕所)

Java对于多线程安全问题提供了专业的解决方式,就是同步代码块。

 Synchronized(对象){需要被同步的代码;}

将买票的例子加上同步代码块:

class Demo 
{
	public static void main(String[] args) 
	{
		Ticket t=new Ticket();
		new Thread(t).start();
		new Thread(t).start();
	}
}
 class Ticket implements Runnable
 {
	 private int ticket=100;
	 public void run()
	 {
		 while(true)
		 {
			 synchronized(new Object())
			 {
			 if(ticket>0)
			 { 
				 try{
					Thread.sleep(50);
				 }catch(Exception e)
				 {
					e.printStackTrace();
				 }
				 System.out.println(Thread.currentThread().getName()+"\t"+(ticket--));
			 }
			 }
		 }
	 }
 }

10多线程(多线程同步代码块)

对象如同锁,持有锁的线程可以在同步中执行,没有持有锁的线程即使获取了cpu的执行权也进不去,因为没有获取锁。

同步的前提:

必须要有2个或者2个以上的线程;

必须是多个线程使用一个锁

必须保证同步中只能有一个线程在运行

好处:解决多线程的安全问题;

劈断:多个线程都需要判断锁,较为消耗资源

11多线程(多线程--同步函数)

需求:银行有一个金库,有两个储户分别存300元,每次存100,存了3次。

class  Demo
{
	public static void main(String[] args) 
	{
		Customer cus=new Customer();
		new Thread(cus).start();
		new Thread(cus).start();
	}
}
class Bank
{
	private int sum;
	public void add(int n)
	{
		synchronized(new Object())
		{
			sum+=n;
			System.out.println("sum="+sum);
		}

	}
}
class Customer implements Runnable
{
	private Bank b=new Bank();
	public void run()
	{
		b.add(100);
	}
}

或者,用同步函数(synchronized 作为修饰符),函数需要被对象调用,那么函数都有一个所属对象引用this,同步函数使用的锁是this。 

代码:

class  Demo
{
	public static void main(String[] args) 
	{
		Customer cus=new Customer();
		new Thread(cus).start();
		new Thread(cus).start();
	}
}
class Bank
{
	private int sum;
	public synchronized void add(int n)
	{
			sum+=n;
			System.out.println("sum="+sum);
	}
}
class Customer implements Runnable
{
	private Bank b=new Bank();
	public void run()
	{
		b.add(100);
	}
}

如果不是同一个锁(即不是同一个对象),可能出现错票。

12多线程(多线程-静态同步函数的锁是class对象)

如果同步函数被静态修饰后,使用的锁匙什么呢?

不是this,因为静态方法中没有this,静态进内存时,内存中没有本类对象,但有该类对应的字节码文件对象,类名.class,该对象类型为Class

如:Synchronized(Ticket.class)

静态的同步方法使用的锁是该方法所在类的字节码文件对象,即类名.class.

13多线程(多线程-单例设计模式)

饿汉式代码:

class Single
{
	private static final Single instance=new Single();
	private Single(){}
	public static Single getInstance()
	{
		return instance;
	}
}

懒汉式代码:

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

懒汉式:延迟加载多线程访问线程不安全,同步代码块(同步函数)低效,使用双重判断,锁是类的字节码文件Single.class.

14多线程(多线程-死锁)

死锁:同步中嵌套同步,而锁却不同。A等待BB等待A,最后,线程都处在等待状态。

15多线程(线程件通信-示例代码)

线程间通讯:其实就是多个线程在操作一个资源,但是操作的动作不同。

代码:

class Demo 
{
	public static void main(String[] args) 
	{
		Resource res=new Resource();
		new Thread(new Input(res)).start();
		new Thread(new Output(res)).start();
	}
}
class Resource
{
	String name;
	String sex;
}
class Input implements Runnable
{
	private Resource res;
	public Input(Resource res)
	{
		this.res=res;
	}
	public void run()
	{
		int x=0;
		while(true)
		{
			if(x==0)
			{
				res.name="mike";
				res.sex="man";
			}else
			{
				res.name="丽丽";
				res.sex="女";
			}
			x=(x+1)%2;
		}
	}
}
class Output implements Runnable
{
	private Resource res;
	public Output(Resource res)
	{
		this.res=res;
	}
	public void run()
	{
		while(true)
		{
			System.out.println(res.name+"---"+res.sex);
		}
	}
}

程序运行结果如下,出现了错误数据,线程不安全。

16多线程(线程间通信-解决安全问题)

使用同步代码块,两个线程必须使用同一个锁,才能保证同步。

class Demo 
{
	public static void main(String[] args) 
	{
		Resource res=new Resource();
		new Thread(new Input(res)).start();
		new Thread(new Output(res)).start();
	}
}
class Resource
{
	String name;
	String sex;
}
class Input implements Runnable
{
	private Resource res;
	public Input(Resource res)
	{
		this.res=res;
	}
	public void run()
	{
		int x=0;
		while(true)
		{
			synchronized(res)
			{
				if(x==0)
				{
					res.name="mike";
					res.sex="man";
				}else
				{
					res.name="丽丽";
					res.sex="女";
				}
				x=(x+1)%2;
			}
		}
	}
}
class Output implements Runnable
{
	private Resource res;
	public Output(Resource res)
	{
		this.res=res;
	}
	public void run()
	{
		while(true)
		{
			synchronized(res)
			{
				System.out.println(res.name+"---"+res.sex);
			}
		}
	}
}

存在的问题:CPU切换一个值,打印一大片。如果交替执行怎么办呢?

17多线程(线程间通信-等待唤醒机制)

等待唤醒机制:

wait(),notify(),notifyAll()都使用在同步中,因为要对持有监视器(锁)的线程操作,所以要使用在同步中,因为只有同步才有锁。

为什么这些操作线程的方法要定义在Object类中呢?

因为这些方法在操作同步线程时,都必须要标识他们所操作线程持有的锁,只有一个锁上的被等待的线程可以被同一个锁上的notify唤醒,不可以对不同锁中的线程进行唤醒,也就是说,等待和唤醒必须是同一个锁,而锁可以是任意对象所以可以被任意对象调用的方法定义在Object类中。

代码:

class Test 
{
	public static void main(String[] args) 
	{
		Resource res=new Resource();
		new Thread(new Input(res)).start();
		new Thread(new Output(res)).start();
	}
}
class Resource
{
	String name;
	String sex;
	boolean flag=false;
}
class Input implements Runnable
{
	private Resource res;
	public Input(Resource res)
	{this.res=res;}
	public void run()
	{
		int x=0;
		while(true)
		{
			synchronized(res)
			{
				if(res.flag)
				{
					try
					{
						res.wait();
					}
					catch (Exception e)
					{
						e.printStackTrace();
					}
				}
				if(x==0)
				{
					res.name="mike";
					res.sex="man";
				}else
				{
					res.name="丽丽";
					res.sex="女";
				}
				x=(x+1)%2;
				res.flag=true;
				res.notify();
			}
			
		}
	}
}
class Output implements Runnable
{
	private Resource res;
	public Output(Resource res)
	{
		this.res=res;
	}
	public void run()
	{
		while(true)
		{
			synchronized(res)
			{
				if(!res.flag)
				{
					try
					{
						res.wait();
					}
					catch (Exception e)
					{
						e.printStackTrace();
					}
				}
				System.out.println(res.name+"---"+res.sex);
				res.flag=false;
				res.notify();
			}

		}
	}
}

运行结果:

18多线程(线程间通信-代码优化)

代码:

class Test 
{
	public static void main(String[] args) 
	{
		Resource res=new Resource();
		new Thread(new Input(res)).start();
		new Thread(new Output(res)).start();
	}
}
class Resource
{
	private String name;
	private String sex;
	private boolean flag=false;
	public synchronized void set(String name,String sex)
	{
		if(this.flag)
		{
			try
			{
				this.wait();
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
		}
		this.name=name;
		this.sex=sex;
		this.flag=true;
		this.notify();
	}
	public synchronized void out()
	{
		if(!this.flag)
		{
			try
			{
				this.wait();
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
		}
		System.out.println(this.name+"---"+this.sex);
		this.flag=false;
		this.notify();
	}
}
class Input implements Runnable
{
	private Resource res;
	public Input(Resource res)
	{
		this.res=res;
	}
	public void run()
	{
		int x=0;
		while(true)
		{
			if(x==0)
			{
				res.set("mike","man");
			}
			else
			{
				res.set("丽丽","女");
			}
			x=(x+1)%2;
		}
	}
}
class Output implements Runnable
{
	private Resource res;
	public Output(Resource res)
	{
		this.res=res;
	}
	public void run()
	{
		while(true)
		{
			res.out();
		}
	}
}

19多线程(线程间通信-生产者 消费者)

对于一个资源,当出现,多个负责生产,多个负责消费的时候怎么办呢?

代码:

class Test 
{
	public static void main(String[] args) 
	{
		Resource res=new Resource();
		Product p=new Product(res);
		Consumer c=new Consumer(res);
		new Thread(p).start();
		new Thread(p).start();
		new Thread(c).start();
		new Thread(c).start();
	}
}
class Resource
{
	private String name;
	private int count=1;
	private boolean flag=false;
	public synchronized void set(String name)
	{
		while(true)
		{
			while(flag)
			{
				try
				{
					this.wait();
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}
			}
			this.name=name+(count++);
			System.out.println(Thread.currentThread().getName()+"生产---"+this.name);
			flag=true;
			this.notifyAll();
		}
	}
	public synchronized void out()
	{
		while(true)
		{
			while(!flag)
			{
				try
				{
					this.wait();
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}
			}
			System.out.println(Thread.currentThread().getName()+"消费------"+this.name+this.count);
			flag=false;
			this.notifyAll();
		}
	}
}
class Product implements Runnable
{
	private Resource res;
	public Product(Resource res)
	{
		this.res=res;
	}
	public void run()
	{
		while(true)
		{
			res.set("商品");
		}
	}
}
class Consumer implements Runnable
{
	private Resource res;
	public Consumer(Resource res)
	{
		this.res=res;
	}
	public void run()
	{
		while(true)
		{
			res.out();
		}
	}
}

对于多个生产者和消费者,为什么要定义while判断标记?

让被唤醒的线程再一次判断标记。

为什么定义notifyAll呢?

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

20多线程(线程间通信-生产者消费者jdk5.0升级版)

希望只唤醒对方,不唤醒本方,怎么办呢?

Jdk1.5中提供了多线程升级解决方案,将同步synchronized替换成了显示的lock操作,将Object中的wait(),notify(),notifyAll(),替换成了Condition对象中的await(),signal(),signalAll(),Condition 对象可以通过lock获取。一个锁可以绑定多个Condition。下面的示例中实现了,本方只唤醒对方的操作:

升级后的代码:

import java.util.concurrent.locks.*;
class  Test
{
	public static void main(String[] args) 
	{
		Resource res=new Resource();
		Product p=new Product(res);
		Consumer c=new Consumer(res);
		new Thread(p).start();
		new Thread(p).start();
		new Thread(c).start();
		new Thread(c).start();
	}
}
class Resource
{
	private String name;
	private int count=1;
	private boolean flag=false;
	private Lock lock=new ReentrantLock();
	private Condition condition_pro=lock.newCondition();
	private Condition condition_con=lock.newCondition();
	public void set(String name)
	{
		lock.lock();
		try
		{
			while(flag)
			{
				condition_pro.await();
			}
			this.name=name+(count++);
			System.out.println(Thread.currentThread().getName()+"生产"+this.name);
			this.flag=true;
			condition_con.signal();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			lock.unlock();
		}
		
	}
	public void out()
	{
		lock.lock();
		try
		{
			while(!flag)
			{
				condition_con.await();
			}
			System.out.println(Thread.currentThread().getName()+"消费---"+this.name);
			flag=false;
			condition_pro.signal();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			lock.unlock();
		}
	}
}
class Product implements Runnable
{
	private Resource res;
	public Product(Resource res)
	{
		this.res=res;
	}
	public void run()
	{
		while(true)
		{
			res.set("商品");
		}
	}
}
class Consumer implements Runnable
{
	private Resource res;
	public Consumer(Resource res)
	{
		this.res=res;
	}
	public void run()
	{
		while(true)
		{
			res.out();
		}
	}
}

21多线程(停止线程)

如何停止线程呢?

只有一种,就是run方法结束。

开启多线程运行,运行代码通常都是循环结构的,只要控制住循环,可以让run方法结束,从而线程结束。

特殊情况:当线程处于冻结状态就不会读取到标记,那么线程就不会结束。

调用interrupt方法:如果线程在调用Object类的wait(),wait(long)wait(long,int)方法,或者该类的join(),join(long),join(long,int),sleep(long)sleep(long,int)方法过程中受阻,则其中断状态将被清除,它将收到一个InterruptedException

当没有指定的方式让冻结的线程恢复到运行状态时,这时需要对冻结状态清除,强制让线程恢复到运行状态中来,这样就可以操作标记,让线程结束。

示例代码:

class Test 
{
	public static void main(String[] args) 
	{
		Thread t1=new Thread(new StopThread());
		Thread t2=new Thread(new StopThread());
		t1.start();
		t2.start();
		int x=0;
		while(true)
		{
			if(x++==60)
			{
				t1.interrupt();
				t2.interrupt();
				break;
			}else
			{
				System.out.println(Thread.currentThread().getName());
			}
		}
	}
}
class StopThread implements Runnable
{
	private boolean flag=true;
	public synchronized void run()
	{
		while(flag)
		{
			try
			{
				this.wait();
			}
			catch (InterruptedException e)
			{
				System.out.println(Thread.currentThread().getName()+"---Exception");
				flag=false;
			}
		}
		System.out.println(Thread.currentThread().getName()+"run---");
	}
}

22多线程(守护线程)

setDaemon()将该线程或用户线程,当正在运行的线程都是守护线程时,jvm退出。

该方法在启动线程前调用t.setDaemon(true)后台线程,前台线程一退出就结束了。

23多线程(join方法)

join():A线程执行到了B线程的join方法时,A就会等待,等B线程执行完,A才执行,join可以用来临时加入线程执行。

代码:

class Test 
{
	public static void main(String[] args) throws Exception
	{
		Thread t1=new Thread(new JoinThread());
		Thread t2=new Thread(new JoinThread());
		t1.start();
		t1.join();
		t2.start();
		for(int x=0;x<80;x++)
		{
			System.out.println("main   "+x);
		}
	}
}
class JoinThread implements Runnable
{
	public void run()
	{
		for(int i=0;i<70;i++)
		{
			System.out.println(Thread.currentThread().getName()+"---"+i);
		}
	}
}

该例子中:t1cpu执行权,主线程冻结,t1结束,主线程恢复。而主线程不管t2.

24多线程(优先级和yield方法)

setPriority() 设置优先级,默认为5

yield()暂停当前正在执行的线程对象,并执行其他线程。

Thread.yield() 临时释放,平均运行。

 

 

---------------------- <a href="http://www.itheima.com"target="blank">ASP.Net+Unity开发</a>、<a href="http://www.itheima.com"target="blank">.Net培训</a>、期待与您交流! ----------------------




 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值