黑马程序员——多线程(Lock、setDaemon、join、setPriority、yield)

-----------android培训java培训、java学习型技术博客、期待与您交流!------------

JDK1.5版本新特性:

提供了多线成的升级解决方案。

将同步Sysnchronized替换成现实Lock操作。

将Object中的wait,notify,notifyAll,替换Condition对象。

该对象可以Lock锁 进行获取。


     private Lock lock = new ReentrantLock();//锁对象 相当于synchronized 

private Condition condition_pro = lock.newCondition();// 生产者的等待与唤醒
private Condition condition_con = lock.newCondition();// 消费者的等待与唤醒

举例程序:

在该例中实现了本方只唤醒对方的操作

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





public 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();
	}

}

class Resource
{
	private String name;
	private int count = 1;
	private boolean flag = false;
	
	private Lock lock = new ReentrantLock();//锁对象 相当于synchronized 
	
	private Condition condition_pro = lock.newCondition();// 生产者的等待与唤醒
	private Condition condition_con = lock.newCondition();// 消费者的等待与唤醒
	
	public  void set(String name) throws InterruptedException
	{
		lock.lock();//加锁
			try {
				while(flag)
					condition_pro.await();
				this.name = name + "__"+count++;
				
				System.out.println(Thread.currentThread().getName()+"...生产者.."+this.name);
				flag = true;
				condition_con.signal();//唤醒一个等待线程
				}
			finally
			{
				lock.unlock();//解锁
			}
	}
	public  void out() throws InterruptedException
	{
		lock.lock();
			try
			{
				while(!flag)
					condition_con.await();
				System.out.println(Thread.currentThread().getName()+"...消费者......"+this.name);
				flag = false;
					condition_pro.signal();
			}
			finally
			{
				lock.unlock();//释放锁的动作一定要执行。
			}
	}
}

class Producer implements Runnable
{
	private Resource res;
	
	Producer(Resource res)
	{
		this.res = res;
	}
	public void run()
	{
		while(true)
		{
			try {
				res.set("+商品+");
			} catch (InterruptedException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
		}
	}
}

class Consumer implements Runnable
{
	private Resource res;
	Consumer(Resource res)
	{
		this.res = res;
	}
	public void run()
	{
		while(true)
		{
			try {
				res.out();
			} catch (InterruptedException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
		}
	}
}

 

停止线程:

stop方法已经过时。


如何停止线程?

只有一种,run方法结束。

开启多线程运行,运行代码通常是循环结构。


只要控制住循环,就可以让run方法结束,也就是线程结束。

<span style="font-family:SimSun;font-size:18px;color:#555555;">/*
 * 特殊情况:
 * 当线程处于冻结状态。
 * 就不会读取到标记。那么线程就不会结束。
 * 
 * 
 * 当没有指定的方法让冻结的线程恢复到运行状态时,这时需要进行清除。
 * 强制让线程恢复到运行状态中来。这样就可以操作标记让线程结束。
 * 
 * Thread类提供该方法interrupt();
 */


class StopThread implements Runnable
{
	private boolean flag = true;
	public synchronized void run()
	{
		while(flag)
		{
			try {
				wait();
			} catch (Exception e) {
				System.out.println(Thread.currentThread().getName()+"...Exception");
				flag = false;
			}
			System.out.println(Thread.currentThread().getName()+"...run");
		}
	}
	public void changeFlog()
	{
		flag = false;
	}
}




public class StopThreadDemo 
{

	public static void main(String[] args) 
	{
		StopThread st = new StopThread();
		
		Thread t1 = new Thread(st);
		Thread t2 = new Thread(st);
		
		t1.start();
		t2.start();
		
		int num =0;
		
		while(true)
		{
			if(num++ == 60)
			{
				//st.changeFlog();
				t1.interrupt();
				t2.interrupt();
				break;
			}
			System.out.println(Thread.currentThread().getName()+"......."+num);
		}
		System.out.println("over");

	}

}
</span>

void setDaemon(boolean on) //将该线程标记为守护线程或用户线程。

该方法必须在线程启动之前调用。

当正在运行的线程都是守护线程时,Java虚拟机退出。

<span style="font-family:SimSun;font-size:18px;color:#555555;">public class StopThreadDemo 
{

	public static void main(String[] args) 
	{
		StopThread st = new StopThread();
		
		Thread t1 = new Thread(st);
		Thread t2 = new Thread(st);
		
		t1.setDaemon(true);//关键位置
		t2.setDaemon(true);
		t1.start();
		t2.start();
		
		int num =0;
		
		while(true)
		{
			if(num++ == 60)
			{
				//st.changeFlog();
				//t1.interrupt();
				//t2.interrupt();
				break;
			}
			System.out.println(Thread.currentThread().getName()+"......."+num);
		}
		System.out.println("over");

	}

}</span>
//主线程结束,子线程在等待状态也结束。
class StopThread implements Runnable
{
	private boolean flag = true;
	public synchronized void run()
	{
		while(flag)
		{
			try {
				wait();//有没有等待都结束
			} catch (Exception e) {
				System.out.println(Thread.currentThread().getName()+"...Exception");
				flag = false;
			}
			System.out.println(Thread.currentThread().getName()+"...run");
		}
	}
	public void changeFlog()
	{
		flag = false;
	}
}
//子线程无线循环  只要主线程结束子线程也结束
class StopThread implements Runnable
{
	private boolean flag = true;
	public  void run()
	{
		while(flag)
		{
			System.out.println(Thread.currentThread().getName()+"...run");
		}
	}
	public void changeFlog()
	{
		flag = false;
	}
}

Public final void join()

throws InterruptedException

等待该线程终止。

<span style="font-family:SimSun;font-size:18px;color:#555555;">class Demo implements Runnable
{
	public void run()
	{
		for(int x = 0 ; x<70;x++)
		{
			System.out.println(Thread.currentThread().getName()+"....."+x);
		}
	}
}


public class JoinDemo 
{

	public static void main(String[] args) throws Exception
	{
		Demo d = new Demo();
		Thread t1 = new Thread(d);
		Thread t2 = new Thread(d);
		t1.start();
		
		t1.join();//t1抢夺cup执行权
		
		t2.start();
		
		for(int x = 0; x<80;x++)
		{
			System.out.println("main..."+x);
		}
		System.out.println("over");
	}

}
</span>

程序运行效果:

t1执行完后,main线程和t2线程才执行。

临时加入一个线程。

join:

当A线程执行到了B线程的join()方法时,A就会等待。等B线程执行完,A才会执行。

 join可以用来临时加入线程执行。


String toString()

返回该线程的字符串表现形式,包括线程名称,优先级和线程组。

优先级代表抢cpu的执行权频率。

所有线程的优先级为5.


setPriority(int newPriority)

更改线程的优先级。

最低优先级、默认优先级、最高优先级

1、5、10

MIN_PRIORITY NORM_PRIORITY MAX_PRIORITY 


public static void yield()

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

减缓当前线程执行的频率。

<span style="font-family:SimSun;font-size:18px;color:#555555;">/*
 * 开发时线程的一般写法
 */


public class ThreadTest {

	public static void main(String[] args) 
	{
		new Thread()
		{
			public void run()
			{
				for(int x= 0 ; x<100;x++)
					System.out.println(Thread.currentThread().getName()+"....."+x);
			}
		}.start();
		
		Runnable r = new Runnable()
		{
			public void run()
			{
				for(int x= 0 ; x<100;x++)
					System.out.println(Thread.currentThread().getName()+"....."+x);
			}
		};
		new Thread(r).start();
	}

}
</span>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值