黑马程序员01_多线程

---------------------- ASP.Net+Unity开发.Net培训、期待与您交流! ----------------------

多线程的创建有两种方法:
1、直接继承Thread

2、实现Runnable接口,然后将实现了Runnable接口的对象传进Thread的对象中。(通过观察源代码会发现,Thread类中的run方法会先判断是否有Runnable类或Runnable子类对象传进来,如果有的话会先调用Runnable类或Runnable子类对象中的run方法)


调用run()和start()的区别:

启动线程调用start()而不是调用run(),这源于多线程的内部机制。调用run()方法,只是单纯地调用run()而不是启动多线程,是单线程。


实现Runnable方式创建线程与继承Thread相比,有两点优点:

1、避免了单线程的缺陷

2、如果几个线程公用一个实现了Runnable接口的对象,那么这几个线程可以共享实现了Runnable接口的对象里面的变量。


使用多线程需要注意的一个重要问题就是线程安全问题

导致线程安全问题的原因是一个线程还没有对共享数据操作完成,其他线程就进来了。

而解决线程安全问题的方法就是使用同步代码块或者同步函数。对于同步函数如果是非静态方法,则它的锁是this,静态方法,它的锁是类的Class对象。


解决懒汉单例设计模式中的安全问题

package com.xiaozhi.java;

class Single {
	private Single() {}// 1、私有化

	private static Single single = null;// 2、静态化、初始化为null

	public static Single getInstance() {
		if (single == null)
			synchronized (single) {
				if (single == null)
					single = new Single();
			}
		return single;
	}
}

线程中容易出现的另一个问题是死锁问题

写一个程序模拟线程的死锁

package com.xiaozhi.threads;  

public class Test {  
	
	//模拟死锁问题
    public static void main(String[] args) {  
       LockInstance lockInstance =new LockInstance();
        Thread thread1=new Thread(new MyRunnable1(lockInstance));  
        Thread thread2=new Thread(new MyRunnable2(lockInstance));  
        thread1.start();  
        thread2.start();  
    }  
}  

class LockInstance{//对公共数据封装成对象,谁拥有数据谁负责对外提供操作数据的方法
	private Object locka=new Object();  
	private Object lockb=new Object();
	
	public Object getLocka() {
		return locka;
	}
	public void setLocka(Object locka) {
		this.locka = locka;
	}
	public Object getLockb() {
		return lockb;
	}
	public void setLockb(Object lockb) {
		this.lockb = lockb;
	}
}

class MyRunnable1 implements Runnable {  
   
	private LockInstance lockInstance;
	
    public MyRunnable1(LockInstance lockInstance) {
		super();
		this.lockInstance = lockInstance;
	}

	@Override  
    public void run() {  
        while(true)  
        {  
            synchronized (lockInstance.getLocka())  
            {  
                System.out.println("Thread-0------------------locka");  
                synchronized (lockInstance.getLockb())   
                {  
                    System.out.println("Thread-0------------------lockb");  
                }  
            }  
        }  
    }  
	
	
}  

class MyRunnable2 implements Runnable {  
	   
	private LockInstance lockInstance;
	
    public MyRunnable2(LockInstance lockInstance) {
		super();
		this.lockInstance = lockInstance;
	}

	@Override  
    public void run() {  
        while(true)  
        {  
        	synchronized (lockInstance.getLockb())  
            {  
                System.out.println("Thread-1------------------lockb");  
                synchronized (lockInstance.getLocka())   
                {  
                    System.out.println("Thread-1------------------locka");  
                }  
            }  
        }  
}}

线程间通信:

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

线程间的通信也会产生安全问题,可以使用等待唤醒机制解决。等待唤醒机制也极大地提高了效率。

Object有几个方法用于线程间通信,wait()、notify()和notifyAll()。这些方法必须在同步代码块或者同步函数中。


写一个程序模拟生产者消费者的程序

package com.xiaozhi.java;

public class ProductCustomTest {
	public static void main(String[] args) {
		Resource resource=new Resource();
		Thread producterThread =new Thread(new Productor(resource));
		Thread consumerThread =new Thread(new Consumer(resource));
		producterThread.start();
		consumerThread.start();
	}

}


class Resource{
	private int num;
	private boolean flag;
	public synchronized void add(){
		while(flag)
			try {this.wait();} catch (InterruptedException e) {}
		num++;
		System.out.println("生产到了第"+num+"个产品!");
		flag=true;
		this.notify();
	}
	
	public synchronized void remove(){
		while(!flag)
			try {this.wait();} catch (InterruptedException e) {}
		System.out.println("消费到了第"+num+"个产品!");
		flag=false;
		this.notify();
	}
}

class Productor implements Runnable{
	private Resource resource;

	public Productor(Resource resource) {
		super();
		this.resource = resource;
	}
	
	@Override
	public void run() {
	
		while(true){
			resource.add();
		}
	}
}

class Consumer implements Runnable{
	private Resource resource;

	public Consumer(Resource resource) {
		super();
		this.resource = resource;
	}
	
	@Override
	public void run() {
	
		while(true){
			resource.remove();
		}
	}
}


JDK的新特性:(适用于多生产者多消费者)

Lock代替了sychronized,Condition中的await()方法、signal()方法、signalAll()方法分别代替了Object的wait()方法、notify()方法、notifyAll(0方法。

Condition对象可以区分一组线程。比如消费者生产者问题中生产者有一组生产的线程,消费者有一组消费的线程。

    package com.xiaozhi.procon2;  
      
    import java.util.concurrent.locks.Condition;  
    import java.util.concurrent.locks.Lock;  
    import java.util.concurrent.locks.ReentrantLock;  
      
    /* 
     * 多生产者多消费者 
     * lock代替sychronized 
     * condition里面的await和signal代替Object的wait和notify 
     * condition可以区分本方线程和对方线程 
     */  
    public class Test {  
      
        public static void main(String[] args) {  
            Resource resource=new Resource();  
            Producer producer1=new Producer(resource);  
            Producer producer2=new Producer(resource);  
            Consumer consumer1=new Consumer(resource);  
            Consumer consumer2=new Consumer(resource);  
            Thread thread1=new Thread(producer1);  
            Thread thread2=new Thread(producer2);  
            Thread thread3=new Thread(consumer1);  
            Thread thread4=new Thread(consumer2);  
            thread1.start();  
            thread2.start();  
            thread3.start();  
            thread4.start();  
        }  
    }  
      
    class Resource{  
        private int num;  
        private boolean flag=false;  
        private Lock lock=new ReentrantLock();  
        private Condition condition_pro=lock.newCondition();  
        private Condition condition_con=lock.newCondition();  
        public  void input()  
        {  
            lock.lock();  
            try {  
                while(flag)  
                    condition_pro.await();  
                num++;  
                System.out.println("商品生产-----------------"+num);  
                flag=true;  
                condition_con.signal();  
            } catch (InterruptedException e) {  
                e.printStackTrace();  
            }finally{  
                lock.unlock();  
            }  
        }  
        public  void output()  
        {  
            lock.lock();  
            try {  
                while(!flag)  
                    condition_con.await();  
                System.out.println("商品消费--------------------------"+num);  
                flag=false;  
                condition_pro.signal();  
            } catch (InterruptedException e) {  
                e.printStackTrace();  
            }finally{  
                lock.unlock();  
            }  
        }  
    }  
      
    class Producer implements Runnable{  
      
        private Resource resource;  
          
        public Producer(Resource resource) {  
            super();  
            this.resource = resource;  
        }  
      
        @Override  
        public void run() {  
            while(true)  
                resource.input();  
        }  
    }  
      
    class Consumer implements Runnable{  
      
        private Resource resource;  
          
        public Consumer(Resource resource) {  
            super();  
            this.resource = resource;  
        }  
      
        @Override  
        public void run() {  
            while(true)  
                resource.output();  
        }  
    }  



停止线程:

通常情况下使用标记来停止线程。wait的线程可以使用interrupte让线程从冻结状态回到运行状态,或者阻塞状态。但是这样会抛出InterruptedException


package com.xiaozhi.procon2;  

public class Test2 {  
    public static void main(String[] args) {  
        MyRun myRun=new MyRun();  
        Thread thread1=new Thread(myRun);  
        Thread thread2=new Thread(myRun);  
        thread1.start();  
        thread2.start();  
        try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}  
        myRun.setFlag(false);  
    }  
}  

class MyRun implements Runnable{  
    private boolean flag=true;  
    @Override  
    public synchronized void run() {  
        while(flag){  
            System.out.println(Thread.currentThread().getName()+"---------------run");  
        }  
    }  
    public void setFlag(boolean flag) {  
        this.flag = flag;  
    }  
      
}  

Join()方法的使用举例:


join()可以使多个线程同时运行,且一个线程运行完等待其他线程运行完再往下运行。

最后附一张线程状态图




---------------------- ASP.Net+Unity开发.Net培训、期待与您交流! ----------------------
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
黑马程序员多线程练习题主要包括两个问题。第一个问题是如何控制四个线程在打印log之前能够同时开始等待1秒钟。一种解决思路是在线程的run方法中调用parseLog方法,并使用Thread.sleep方法让线程等待1秒钟。另一种解决思路是使用线程池,将线程数量固定为4个,并将每个调用parseLog方法的语句封装为一个Runnable对象,然后提交到线程池中。这样可以实现一秒钟打印4行日志,4秒钟打印16条日志的需求。 第二个问题是如何修改代码,使得几个线程调用TestDo.doSome(key, value)方法时,如果传递进去的key相等(equals比较为true),则这几个线程应互斥排队输出结果。一种解决方法是使用synchronized关键字来实现线程的互斥排队输出。通过给TestDo.doSome方法添加synchronized关键字,可以确保同一时间只有一个线程能够执行该方法,从而实现线程的互斥输出。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [黑马程序员——多线程10:多线程相关练习](https://blog.csdn.net/axr1985lazy/article/details/48186039)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值