Q:sleep,yield,join,wait,notify,notifyAll区别
A:sleep和yield是线程的静态方法,直接用类名就可以调用,join是普通方法,需要实例对象调用,wait,notify,notifyAll是属于Object的方法.下面分开介绍一下他们的用法:
sleep:Thread.sleep(long mills),让当前线程进入睡眠状态,不会释放锁和资源,只要等阻塞时间过去就会进入就绪状态,可以使用interrupt方法打断线程,但是可能会抛出interruptException.
yield:Thread.yeild(),当前线程进入就绪状态,但是虚拟机会优先调用就绪队列中的优先级最高的线程,代表如果当前线程的优先级高,还是会继续运行.
join:线程调用该方法,当前线程会让调用线程先执行完毕后再继续运行,但是该方法会抛出异常.注意捕获.
wait,notify,notifyAll:wait和notify,notifyAll需要在同步代码中调用,用于多个线程之间共享数据存取,进入睡眠状态并自动的释放锁和资源,必须要调用notify和notifyAll来唤醒, 当有线程调用notify和notifyAll唤醒睡眠线程时,该线程只是从锁的等待状态进入就绪状态,但是线程并不是能够马上执行的,还是需要唤醒线程执行完,释放锁和资源,线程到获取锁和资源才进入运行.
public class ThreadTest {
public static void main(String[] args) {
// Thread1 thread1 = new Thread1();
// Thread2 thread2 = new Thread2();
// Thread t1 = new Thread(thread1);
// Thread t2 = new Thread(thread2);
// t1.start();
// new Thread(new Runnable() {
//
// @Override
// public void run() {
// try {
// Thread.sleep(2000);
// System.out.println(Thread.currentThread().getName());
// } catch (Exception e) {
// e.printStackTrace();
// }
//
// }
// },"Thread-11 sleep...").start();
// t2.start();
// ProducerTest producerTest = new ProducerTest();
// Thread t1 = new Thread(producerTest);
// t1.start();
//
// Consumer consumer = new Consumer();
// Consumer consumer2 = new Consumer();
// Consumer consumer3 = new Consumer();
//
//
// new Thread(consumer).start();
// new Thread(consumer2).start();
// new Thread(consumer3).start();
// new Thread(new Producter()).start();
// new Thread(new Consume()).start();
Thread3 thread3 = new Thread3();
Thread3 thread32 = new Thread3();
Thread t1 = new Thread(thread3, "thread1-ax");
Thread t2 = new Thread(thread32, "thread2-ou");
t1.start();
try {
t1.join(100000);
} catch (InterruptedException e) {
e.printStackTrace();
}
t2.start();
}
//缓冲区最大容量
private static int MAX_CAPACITY = 5;
//用一个ArrayList做缓冲区
private static List<UserInfo> list = new ArrayList<UserInfo>();
static class Producter implements Runnable {
@Override
public void run() {
//循环生产产品
while(true) {
//获取缓冲区的锁
synchronized (list) {
//如果缓冲区已满
while(list.size() > MAX_CAPACITY) {
try {
System.out.println("当前产品个数:" + list.size() + ",已经达到最大的数量");
//调用wait(),释放锁
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("当前产品个数:" + list.size());
//缓冲区未满,添加数据
list.add(new UserInfo());
System.out.println("生产一个产品,当前产品个数为:" + list.size());
//生产完一个产品后,通知所有阻塞在wait()调用中的线程
list.notifyAll();
try {
Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
//创建消费者
static class Consume implements Runnable {
@Override
public void run() {
while(true) {
synchronized(list) { //获取缓冲区的锁
while(list.size()==0) { //如果缓冲区为空,
try {
System.out.println("当前产品个数为" + list.size() + ",等待生产者生产。。。");
list.wait(); //则进行阻塞,并释放缓冲区的锁
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("当前产品个数为" + list.size());
//缓冲区不空,则消费一个产品
list.remove(0);
System.out.println("消费了一个产品,当前产品个数为" + list.size());
list.notifyAll(); //消费一个产品之后,通知所有阻塞在wait调用上的线程
try {
Thread.sleep(4000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
}
//测试sleep阻塞线程
class Thread1 implements Runnable{
@Override
public void run() {
System.out.println("thread1 sleep start...");
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
System.err.println("thread1 sleep end...");
}
}
//测试wait阻塞线程(生产者消费者模式wait,notify,notifyAll)
class Thread2 implements Runnable{
@Override
public void run() {
System.out.println("thread2 wait start...");
try {
//会抛出java.lang.IllegalMonitorStateException
//因为在非同步的代码调用这个方法
wait(1000);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("thread2 wait end...");
}
}
//测试join/yield
class Thread3 implements Runnable {
@Override
public void run() {
for(int i = 0; i < 10; i ++) {
if(i == 5) {
Thread.yield();
}
System.out.println(Thread.currentThread().getName() + "::" + i);
}
}
}
Q:interruptException异常的发生情况?
A:发生interruptException的方法有Thread的sleep,join和Object的wait方法.当线程进入等待状态时候,调用interrupt方法打断当前中断状态,从而抛出这个异常.一般情况下我们会调用isInterrupted方法来获取当前的打断状态,避免抛出异常,同样我们也可以通过Thread.interrupted来获取并清除打断状态.实例如下:
public class InterrupttedExcepionTest {
public static void main(String[] args) {
ThreadInterrupt threadInterrupt = new ThreadInterrupt();
Thread thread = new Thread(threadInterrupt);
// Thread2 thread2 = new Thread2();
// Thread2 thread3 = new Thread2();
// Thread t = new Thread(thread2, "thread-01");
// Thread t2 = new Thread(thread3);
thread.start();
// t.start();
// t.interrupt();
// t2.start();
// t2.interrupt();
thread.interrupt();
// t.interrupt();
}
}
class ThreadInterrupt implements Runnable {
@Override
public void run() {
test();
}
// private synchronized void test() {
// System.out.println("ThreadInterrupt is running...");
// while(true) {
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
//
// if(Thread.currentThread().isInterrupted()) {
// System.out.println("ThreadInterrupt has interruptted...");
// break;
// }
//
// Thread.yield();
// }
// }
private synchronized void test() {
System.out.println("ThreadInterrupt is running...");
while(true) {
if(Thread.currentThread().isInterrupted()) {
System.out.println("ThreadInterrupt has interruptted...");
break;
}
try {
Thread.sleep(1000);
// wait();
// Thread2 thread2 = new Thread2();
// Thread t2 = new Thread(thread2);
// t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Thread2 implements Runnable {
@Override
public void run() {
while(true) {
try {
Thread.sleep(10000);
} catch (Exception e) {
e.printStackTrace();
System.out.println(Thread.currentThread().getName() + " was interrupted.\n"
+ "isInterrupted():" );
}
if(Thread.currentThread().isInterrupted()) {
System.out.println(Thread.currentThread().getName());
break;
}
}
}
}
Q:为什么线程要同步?
A:java允许多线程操作共享资源,但是这样会导致线程之间发生冲突,因此我们加入同步代码锁保证线程调用时其他线程不会调用,从而保证数据的准确性和一致性.
Q:并发与并行
A:并发:同一时间段或时间点上交替执行的线程或进程;
并行:同一时间段或时间点上一同执行的线程或进程.
Q:线程中的锁?
A:线程中我们常用的锁有三种,synchronized,接口lock和本地变量ThreadLocal,下面我们介绍一下用法:
/模拟银行存取钱
public class Bank {
// private int count = 0;
// a.volatile关键字为域变量的访问提供了一种免锁机制
// b.使用volatile修饰域相当于告诉虚拟机该域可能会被其他线程更新
// c.因此每次使用该域就要重新计算,而不是使用寄存器中的值
// d.volatile不会提供任何原子操作,它也不能用来修饰final类型的变量
// private volatile int count = 0;
// //存钱
// public void addMoney(int money) {
// count += money;
// System.out.println(System.currentTimeMillis() + "存进:" + money);
// }
//
// //取钱
// public void subMoney(int money) {
// if(count < money) {
// System.out.println(System.currentTimeMillis() + "余额不足");
// return;
// }
//
// count -= money;
// System.out.println(System.currentTimeMillis() + "取出:" + money);
// }
//
// //查询
// public void getMoney() {
// System.out.println("卡上余额:" + count);
// }
// //同步方法
// public synchronized void addMoney(int money) {
// count += money;
// System.out.println(System.currentTimeMillis() + "存进:" + money);
// }
// public synchronized void subMoney(int money) {
// if(count < money) {
// System.out.println(System.currentTimeMillis() + "余额不足");
// return;
// }
//
// count -= money;
// System.out.println(System.currentTimeMillis() + "取出:" + money);
// }
// public void getMoney() {
// System.out.println("卡上余额:" + count);
// }
// public void addMoney(int money) {
// synchronized (this) {
// count += money;
// }
// System.out.println(System.currentTimeMillis() + "存进:" + money);
// }
//
// public void subMoney(int money) {
// synchronized (this) {
// if(count < money) {
// System.out.println(System.currentTimeMillis() + "余额不足");
// return;
// }
//
// count -= money;
// }
// System.out.println(System.currentTimeMillis() + "取出:" + money);
// }
//
// public void getMoney() {
// System.out.println("卡上余额:" + count);
// }
//使用ReentrantLock类是可重入、互斥、实现了Lock接口的锁, 它与使用synchronized方法和
//代码块具有相同的基本行为和语义,并且扩展了其能力。
// private Lock lock = new ReentrantLock();
//
// public void addMoney(int money) {
// lock.lock();//上锁
// try {
// count += money;
// System.out.println(System.currentTimeMillis() + "存进:" + money);
// } finally {
// lock.unlock();//释放锁
// }
// }
//
// public void subMoney(int money) {
// lock.lock();//上锁
// try {
// if(count < money) {
// System.out.println(System.currentTimeMillis() + "余额不足");
// return;
// }
//
// count -= money;
// System.out.println(System.currentTimeMillis() + "取出:" + money);
// }finally{
// lock.unlock();//释放锁
// }
// }
// public void getMoney() {
// System.out.println("卡上余额:" + count);
// }
private static ThreadLocal<Integer> count = new ThreadLocal<Integer>(){
@Override
protected Integer initialValue() {
return 0;
}
};
public void addMoney(int money) {
count.set(count.get()+money);
System.out.println(System.currentTimeMillis() + "存进:" + money);
}
public void subMoney(int money) {
if (count.get() - money < 0) {
System.out.println("余额不足");
return;
}
count.set(count.get()- money);
System.out.println(+System.currentTimeMillis() + "取出:" + money);
}
public void getMoney() {
System.out.println("卡上余额:" + count.get());
}
}
上面是不同锁情况下的方式:
//线程同步测试
public class SynchronizedTest {
public static void main(String[] args) {
final Bank bank=new Bank();
Thread tadd=new Thread(new Runnable() {
@Override
public void run() {
while(true){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
bank.addMoney(100);
bank.getMoney();
System.out.println("\n");
}
}
});
Thread tsub = new Thread(new Runnable() {
@Override
public void run() {
while(true){
bank.subMoney(100);
bank.getMoney();
System.out.println("\n");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
tsub.start();
tadd.start();
}
}
Q:解释synchronized,lock和ThreadLocal,说说区别和联系?
A:synchronized:Java语言的关键字,用来修饰代码块,方法和类.修饰普通方法作用域是当前对象,修饰静态方法属于当前类,修饰代码块属于当前对象,修饰类属于当前类.修饰代码块的时候当一个线程访问该对象的同步代码块时,另一个线程仍可以访问这个类的非同步代码块.同时我们需要注意的是在多线程情况下要注意死锁,如例:当多线程情况下,定义两个对象Object,两个同步代码块或者方法对这两个对象的加锁顺序不一样时,线程调用的时候就会发生锁竞争情况,造成死锁.
轻量级锁lock:接口lock属于java.util.concurrent.locks下面的接口,其中常用的方法有lock(),tryLock(),tryLock(long time, TimeUtil time),lockInterruptibly(),unlock(),其中lock是获取锁,但是这个锁必须要释放,通常和try{}finally{}联合使用,finally使用unlock释放锁;tryLock()获取锁成功ture,失败false,这个是立即执行的;tryLock(long time, TimeUtil time)在刚开始或者等待时间内获取锁返回true,否则返回false;lockInterruptibly()当通过这个方法去获取锁时,如果线程正在等待获取锁,则这个线程能够响应中断,即中断线程的等待状态.也就使说,当两个线程同时通过lock.lockInterruptibly()想获取某个锁时,假若此时线程A获取到了锁,而线程B只有在等待,那么对线程B调用threadB.interrupt()方法能够中断线程B的等待过程.
我们在使用lock的时候,会使用ReentrantLock这个唯一实现类,提供了更加丰富的方法,其中实现类ReentrantReadWriteLock最重要的就是readLock和writeLock.其中规则是:读读不互斥,读写互斥,写写互斥.
ThreadLocal是线程本地变量,它为每个副本都创建了一个副本,每个线程都会访问自己内部的副本变量.当有不许需要共享的变量(数据库的链接)出现时,我们就可以使用ThreadLocal处理.它会将其存储在ThreadLocals中,以键值对形式存在.
区别:lock是一个接口,synchronized是java内部的关键字;synchronized发生异常的时候,会主动释放锁和资源,不会发生死锁,但是lock不同,一般需要在finally中调用释放锁的方法;使用lock可以让等待锁的线程中断响应,但是synchronized不行;lock可以知道获取锁是否成功,可以提高多线程的读取效率.
Q:同步的原子性和可见性
A:原子性是指将线程通过锁(synchronized)使其操作变成一个整体,要么整体成功,要么整体失败;可见性是指一个线程的修改状态对于其他线程是可见.