---------------------- 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培训、期待与您交流! ----------------------