多线程代码终结篇
-
手写一个生产者消费者模型吧
//主线程逻辑:定义一个仓库对象,把对象传给生产者和消费者线程。其中二者共用同一把锁,因此是阻塞的。 public class producer_consumer { public static void main(String[] args) { Product p = new Product(); Thread p1 = new Thread(new Producer(p)); Thread c1 = new Thread(new Consumer(p)); p1.start(); c1.start(); } } //仓库类,里面变量是数量和阈值 class Product { int num = 0; int threshold = 10; } //生产者的逻辑:锁住仓库对象,一旦小于阈值就生产,生产完了就通知所有人,自己进入等待模式wait释放锁。 class Producer implements Runnable{ private Product product; Producer(Product product) { this.product = product; } @Override public void run() { while (true){ synchronized (product){ if (product.num < product.threshold){ product.num++; System.out.println("我是生产者,我生产了第"+product.num+"个"); try { Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } product.notifyAll(); }else { try { product.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } } } //消费者的逻辑:当数量大于0的时候,就往里面拿,拿完告诉生产者们继续生产,然后进入等待wait释放锁 class Consumer implements Runnable{ private Product product; Consumer(Product product) { this.product = product; } @Override public void run() { while (true){ synchronized (product){ if (product.num > 0){ System.out.println("我是消费者,我消费了第"+product.num+"个"); product.num--; try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } product.notifyAll(); }else { try { product.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } } }
-
手写一个交替打印1-100
public class Test100_02 { private static Object object = new Object(); private static boolean isFlag = false; public static void main(String[] args) { Thread t1 = new Thread(() -> { for (int i = 1; i <= 999; i+=2) { synchronized (object) { if (!isFlag) { System.out.println("thread 【1】 current:" + i); isFlag = true; try { object.notify(); object.wait(); } catch (InterruptedException e) { e.printStackTrace(); } // object.notify(); } } } }); Thread t2 = new Thread(() -> { for (int i = 2; i <= 1000; i+=2) { synchronized (object) { if (isFlag) { isFlag = false; System.out.println("thread 【2】 current:" + i); object.notify(); try { // object.wait();不能交换wait和notify的位置 object.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } }); //设置优先级是为了保证第一个线程先执行。 t1.setPriority(Thread.MAX_PRIORITY); t1.start(); t2.start(); } }
-
手写一个交替打印ABC
public class MyThreadPrinter2 implements Runnable {
private String name;
private Object prev;
private Object self;
private MyThreadPrinter2(String name, Object prev, Object self) {
this.name = name;
this.prev = prev;
this.self = self;
}
@Override
public void run() {
int count = 10;
while (count > 0) {
synchronized (prev) {
synchronized (self) {
System.out.print(name);
count--;
try{
Thread.sleep(1);
}
catch (InterruptedException e){
e.printStackTrace();
}
self.notify();
}
try {
prev.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) throws Exception {
Object a = new Object();
Object b = new Object();
Object c = new Object();
MyThreadPrinter2 pa = new MyThreadPrinter2("A", c, a);
MyThreadPrinter2 pb = new MyThreadPrinter2("B", a, b);
MyThreadPrinter2 pc = new MyThreadPrinter2("C", b, c);
new Thread(pa).start();
Thread.sleep(10);
new Thread(pb).start();
Thread.sleep(10);
new Thread(pc).start();
Thread.sleep(10);
}
}
ThreadLocalDemo!!!每个线程自己的变量按照自己的逻辑增加。
public class ThreadLocalDemo extends Thread{
private ResultData data;
public ThreadLocalDemo(ResultData data) {
this.data = data;
}
@Override
public void run() {
for (int i = 0; i < 3; i++) {
System.out.println(Thread.currentThread().getName() + "---" + "i---" + i + "--num:" + data.getNum());
}
}
public static void main(String[] args) throws InterruptedException {
ResultData data = new ResultData();
ThreadLocalDemo threadLocaDemo1 = new ThreadLocalDemo(data);
ThreadLocalDemo threadLocaDemo2 = new ThreadLocalDemo(data);
ThreadLocalDemo threadLocaDemo3 = new ThreadLocalDemo(data);
threadLocaDemo1.start();
threadLocaDemo2.start();
threadLocaDemo3.start();
Thread.sleep(300);
System.out.println(ResultData.count);
}
}
class ResultData{
// 生成序列号共享变量
public static Integer count=0;
private static ThreadLocal<Integer> threadLocal=new ThreadLocal<Integer>(){
protected Integer initialValue() {
return 0;
}
};
public Integer getNum() {
int count = threadLocal.get() + 1;
threadLocal.set(count);
return count;
}
}