1.写一个死锁程序:
public class DeadLock {
/**
* @param args
*/
public static void main(String[] args) {
new Thread(new MyThread(false)).start();
new Thread(new MyThread(true)).start();
}
}
class DeadL {
/*创建两个锁对象*/
static Object obja = new Object();
static Object objb = new Object();
}
class MyThread implements Runnable {
private boolean flag;
MyThread(boolean flag) {
this.flag = flag;
}
public void run() {
if(flag) {
synchronized (DeadL.obja) {
System.out.println("if locka");
synchronized (DeadL.objb) {
System.out.println("if lockb");
}
}
}else {
synchronized (DeadL.objb) {
System.out.println("else lockb");
synchronized (DeadL.obja) {
System.out.println("else locka");
}
}
}
}
}
2.写一个生产者消费者程序:
public class ProductAndConsumer {
public static void main(String[] args) {
Resource r = new Resource();
new Thread(new Product(r)).start();
new Thread(new Consumer(r)).start();
new Thread(new Product(r)).start();
new Thread(new Consumer(r)).start();
new Thread(new Consumer(r)).start();
}
}
class Resource {
private String name;
private int age = 0;
private boolean flag;
public synchronized void set(String name) {
while(flag)
try {
this.wait(); //让当前线程等待
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.name = name +"--"+age++;
flag = true;
this.notifyAll(); //唤醒在此对象监视器上等待的所有线程
}
public synchronized void out() {
while(!flag)
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(name);
flag = false;
this.notifyAll();
}
}
class Product implements Runnable {
private Resource r;
public Product(Resource r) {
this.r = r;
}
public void run() {
int x = 0;
while(true) {
if(x==0) {
r.set("丽丽");
}else {
r.set("lili");
}
x = (x+1)%2;
}
}
}
class Consumer implements Runnable {
private Resource r;
public Consumer(Resource r) {
this.r = r;
}
public void run() {
while(true) {
r.out();
}
}
}
3.写一个程序,能够控制多线程的执行顺序:
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ThreadSortCondition {
public static void main(String[] args) {
final MyThreadCondition myCondition = new MyThreadCondition();
for(int i=0;i<20;i++) {
//开启三个线程
new Thread(new Runnable() {
public void run() {
myCondition.main();
}
}).start();
new Thread(new Runnable() {
public void run() {
myCondition.sub2();
}
}).start();
new Thread(new Runnable() {
public void run() {
myCondition.sub3();
}
}).start();
}
}
}
class MyThreadCondition {
private int x = 1;
//创建锁对象(锁是控制多个线程对共享资源进行访问的工具)
private Lock lock = new ReentrantLock();
//创建Condition对象(Condition 替代了 Object 监视器方法的使用)
Condition con1 = lock.newCondition();
Condition con2 = lock.newCondition();
Condition con3 = lock.newCondition();
public void main() {
try {
//获取锁
lock.lock();
while(x!=1)
try {
//当前线程在接到信号或被中断之前一直处于等待状态。
con1.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
for(int i=0;i<50;i++) {
System.out.println("main-----------"+i);
}
x = 2;
//唤醒所有等待线程
con2.signal();
}finally {
// 释放锁
lock.unlock();
}
}
public void sub2() {
try {
lock.lock();
while(x!=2)
try {
con2.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
for(int i=0;i<10;i++) {
System.out.println("sub2---------"+i);
}
x = 3;
con3.signal();
}finally {
lock.unlock();
}
}
public void sub3() {
try {
lock.lock();
while(x!=3)
try {
con3.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
for(int i=0;i<10;i++) {
System.out.println("sub3---"+i);
}
x = 1;
con1.signal();
}finally {
lock.unlock();
}
}
}
4.设计一个缓冲系统:
缓冲系统:当外界向缓冲系统去数据时,如果缓冲系统有数据就直接返回给获取者;如果缓冲系统没有数据时,系统查询数据库,将数据返给系统,系统再取数据给获取者。
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class CacheSystem {
private Map<String,Object> map = new HashMap<String,Object>();
public static void main(String[] args) {
}
//创建读写锁对象(读与读线程可以同步,读与写、写与写线程是互斥)
private ReentrantReadWriteLock rwlock = new ReentrantReadWriteLock();
//从缓冲系统取数据
public Object getData(String key) {
Object data = null;
Object value = null;
try {
//获取读锁
rwlock.readLock().lock();
value = map.get(key);
if(value==null) {
try {
//数据不存在,释放读锁,获取写锁
rwlock.readLock().unlock();
rwlock.writeLock().lock();
if(value==null) { //如果线程1拿到写锁,开始写完数据,释放写锁后,线程2拿到写锁,这时线程2就不用在写数据了!
//写数据
data = "dadas"; //从数据库查找数据(queryDB())
map.put("data", data);
}
} finally {
//释放写锁
rwlock.writeLock().unlock();
}
//获取读锁
rwlock.readLock().lock();
}}finally {
//读到数据后,释放读锁
rwlock.readLock().unlock();
}
//获取数据
return data;
}
}
5.线程池与任务调度程序:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class ThreadPool {
/**
* @param args
*/
public static void main(String[] args) {
// 创建线程池对象(池里有10个线程)
ExecutorService threadPool = Executors.newFixedThreadPool(10);
//创建缓冲线程池对象
ExecutorService threadPool1 = Executors.newCachedThreadPool();
//创建单个线程对象,可以实现线程池死掉后重新启动
ExecutorService threadPool2 = Executors.newSingleThreadExecutor();
for(int j=0;j<7;j++) {
final int task = j;
//执行一个任务
threadPool.execute(new Runnable() {
public void run() {
// TODO Auto-generated method stub
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(int i=0;i<10;i++) {
System.out.println(Thread.currentThread().getName()+"--"+i+"____"+task);
}
}
});
}
//执行任务调度
Executors.newScheduledThreadPool(3).scheduleAtFixedRate(
new Runnable() {
public void run() {
// TODO Auto-generated method stub
System.out.println("珊,我爱你!!!!!");
}
},
10, //程序运行10'后执行,之后每隔3秒执行一次
3,
TimeUnit.SECONDS);
}
}