黑马程序员---Java多线程(1)

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

1.多线程的实现

在java中要想实现多线程,有两种手段,一种是继续Thread类,另外一种是实现Runable接口。

对于直接继承Thread的类来说,代码大致框架是:

class 类名 extends Thread{

方法1;

方法2;

…

public void run(){

// other code…

}

属性1;

属性2;

…


}

通过实现Runnable接口:

大致框架是:

class 类名 implements Runnable{

方法1;

方法2;

…

public void run(){

// other code…

}

属性1;

属性2;

…

}

关于选择继承Thread还是实现Runnable接口?

其实Thread也是实现Runnable接口的

class Thread implements Runnable {
//…
public void run() {
if (target != null) {
target.run();
}
}
}

其实Thread中的run方法调用的是Runnable接口的run方法。可以看出,Thread和Runnable都实现了run方法,这种操作模式其实就是代理模式。

Thread和Runnable的区别:

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

class hello extends Thread {
public void run() {
for (int i = 0; i < 7; i++) {
if (count > 0) {
System.out.println("count= " + count--);
}
}
}
public static void main(String[] args) {
hello h1 = new hello();
hello h2 = new hello();
hello h3 = new hello();
h1.start();
h2.start();
h3.start();
}
private int count = 5;
}

【运行结果】:

count= 5

count= 4

count= 3

count= 2

count= 1

count= 5

count= 4

count= 3

count= 2

count= 1

count= 5

count= 4

count= 3

count= 2

count= 1

大家可以想象,如果这个是一个买票系统的话,如果count表示的是车票的数量的话,说明并没有实现资源的共享。

我们换为Runnable接口

class MyThread implements Runnable{
private int ticket = 5; //5张票
public void run() {
for (int i=0; i<=20; i++) {
if (this.ticket > 0) {
System.out.println(Thread.currentThread().getName()+ "正在卖票"+this.ticket--);
}
}
}
}
public class lzwCode {
public static void main(String [] args) {
MyThread my = new MyThread();
new Thread(my, "1号窗口").start();
new Thread(my, "2号窗口").start();
new Thread(my, "3号窗口").start();
}
}

【运行结果】:

count= 5

count= 4

count= 3

count= 2

count= 1

总结:

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

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

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

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

2.线程的几种状态

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()方法,该线程结束生命周期。




注意:main方法其实也是一个线程。在java中所以的线程都是同时启动的,至于什么时候,哪个先执行,完全看谁先得到CPU的资源。
在java中,每次程序运行至少启动2个线程。一个是main线程,一个是垃圾收集线程。

3.线程的安全

线程安全产生的原因:
1. 多个线程在操作共享数据
2. 操作共享数据的线程代码有多条

解决方法1:同步代码块
格式如下:
synchronized (同步对象) {
			
		}
同步代码块中的同步对象可以为任意的对象。一般设为this即可,也可以自定义
public class tacket implements Runnable{
	private int num = 100;
	Object obj = new Object();
	@Override
	public void run() {
		// TODO Auto-generated method stub
		sale();
	}
	public void sale(){
		while(true){
			synchronized (obj) {
				if(num>0){
				try {
					Thread.sleep(10);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				    System.out.println(Thread.currentThread().getName()+"***"+num--);
				}
				else 
				{
				break;
			    }	
			}	
		}
	}
	public static void main(String[] args) {
		tacket t = new tacket();
		Thread t1 = new Thread(t);
		Thread t2 = new Thread(t);
		t1.start();
		t2.start();
	}
}
解决方案2:同步函数
上面的代码可以改为:
	public void run() {
		// TODO Auto-generated method stub
		sale();
	}
	/**
	 * 
	 */
	public void sale(){
		while(true){
			show();	
		}
	}
	public synchronized void show(){
		if(num>0){
			try {
				Thread.sleep(10);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			    System.out.println(Thread.currentThread().getName()+"***"+num--);
			}	
	}
注意:线程函数也是有线程锁的,使用的是this。但是如果是静态线程函数,使用的锁是该函数所属的字节码文件对象,可以用 this.getclass() 或者 类名.class 获取

当多个线程共享一个资源的时候需要进行同步,但是过多的同步可能导致死锁。

死锁的例子:
public class Test implements Runnable{
	private boolean flag;
	public Test(boolean flag){
		this.flag = flag;
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		if(flag){
			while(true)
				synchronized (MyLock.locka) {
				System.out.println(Thread.currentThread().getName()+"---if....locka");
				synchronized (MyLock.lockb) {
					System.out.println(Thread.currentThread().getName()+"---if....lockb");
				}
			}
		}else {	
			while(true)
				synchronized (MyLock.lockb) {
				System.out.println(Thread.currentThread().getName()+"---else....lockb");
				synchronized (MyLock.locka) {
					System.out.println(Thread.currentThread().getName()+"---else....locka");
				}
			}
		}
	}
}
public class MyLock {
	public static final Object locka = new Object();
	public static final Object lockb = new Object();
}
public class Demo {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Test t1 = new Test(false);
		Test t2 = new Test(true);
		
		Thread x = new Thread(t1);
		Thread y = new Thread(t2);
		
		x.start();
		y.start();
	}

}

程序执行结果:
Thread-0---else....lockb
Thread-1---if....locka
没有后续了,直接锁死了。

















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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值