package com.i9i.rpc;
import java.lang.reflect.Field;
import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicIntegerArray;
import java.util.concurrent.atomic.AtomicMarkableReference;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicReferenceArray;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import java.util.concurrent.atomic.AtomicStampedReference;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import sun.misc.Unsafe;
public class ThreadTest {
/**
* 定义线程池
*/
static ThreadPoolExecutor executor = new ThreadPoolExecutor(50, 100, 100000, TimeUnit.MINUTES,
new ArrayBlockingQueue<>(100000));
public static void atomicReferenceFieldUpdator() {
User u = new User(1, "张三");
AtomicReferenceFieldUpdater<User, Integer> fieldUpdater = AtomicReferenceFieldUpdater.newUpdater(User.class,
Integer.class, "id");
fieldUpdater.compareAndSet(u, u.getId(), 2);
System.out.println(u);
}
public static void atomicReference() {
User[] arr = { new User(1, "张三"), new User(2, "李四") };
// AtomicIntegerArray aia=new AtomicIntegerArray(4);
AtomicReference<User> aia = new AtomicReference(arr[0]);
int index = 1;
aia.compareAndSet(arr[index], new User(3, "王五"));// 不会改变arr中原来的值,AtomicIntegerArray内部创建了一个新的数组clone原来的值
System.out.println("arr原来的值:" + arr[index] + " aia中的值:" + aia.get());
aia.get().setId(3);
System.out.println("arr原来的值:" + arr[0] + " aia中的值:" + aia.get());
}
public static void atomicStampedReference() {
User[] arr = { new User(1, "张三"), new User(2, "李四") };
// AtomicIntegerArray aia=new AtomicIntegerArray(4);
AtomicStampedReference<User> asr = new AtomicStampedReference<ThreadTest.User>(arr[0], 0);
int index = 1;
asr.compareAndSet(arr[index], new User(3, "王五"), 0, 1);// 不会改变arr中原来的值,AtomicIntegerArray内部创建了一个新的数组clone原来的值
System.out.println("arr原来的值:" + arr[index] + " aia中的值:" + asr.getReference());
asr.compareAndSet(new User(3, "王五"), new User(3, "王五2"), 1, 1);
System.out.println("arr原来的值:" + arr[0] + " aia中的值:" + asr.getReference());
asr.compareAndSet(new User(3, "王五"), new User(3, "王五4"), 0, 1);
System.out.println("arr原来的值:" + arr[0] + " aia中的值:" + asr.getReference());
}
public static void atomicMarkableReference() {
User[] arr = { new User(1, "张三"), new User(2, "李四") };
// AtomicIntegerArray aia=new AtomicIntegerArray(4);
int index = 1;
AtomicMarkableReference<User> aia = new AtomicMarkableReference(arr[index], true);
aia.compareAndSet(arr[index], new User(3, "王五"), true, true);// 不会改变arr中原来的值,AtomicIntegerArray内部创建了一个新的数组clone原来的值
System.out.println("arr原来的值:" + arr[index] + " aia中的值:" + aia.getReference());
}
public static void atomicReferenceArray() {
User[] arr = { new User(1, "张三"), new User(2, "李四") };
// AtomicIntegerArray aia=new AtomicIntegerArray(4);
AtomicReferenceArray<User> aia = new AtomicReferenceArray(arr);
int index = 1;
aia.compareAndSet(index, arr[index], new User(3, "王五"));// 不会改变arr中原来的值,AtomicIntegerArray内部创建了一个新的数组clone原来的值
System.out.println("arr原来的值:" + arr[index] + " aia中的值:" + aia.get(index));
aia.get(0).setId(3);
System.out.println("arr原来的值:" + arr[0] + " aia中的值:" + aia.get(0));
}
static class User {
volatile Integer id;
private String name;
public User() {
super();
}
public User(Integer id, String name) {
super();
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + "]";
}
}
public static void atomicArray() {
int[] arr = new int[4];
// AtomicIntegerArray aia=new AtomicIntegerArray(4);
AtomicIntegerArray aia = new AtomicIntegerArray(arr);
int index = 0;
aia.compareAndSet(index, arr[index], 1);// 不会改变arr中原来的值,AtomicIntegerArray内部创建了一个新的数组clone原来的值
System.out.println("arr原来的值:" + arr[index] + " aia中的值:" + aia.get(index));
AtomicIntegerArray aia2 = new AtomicIntegerArray(4);
int index2 = 2;
aia.compareAndSet(index, aia.get(index), 231);// 不会改变arr中原来的值,AtomicIntegerArray内部创建了一个新的数组clone原来的值
System.out.println(" aia2中的值:" + aia.get(index));
}
public static void condition() {
Lock lock = new ReentrantLock();// 创建非公平锁,效率更高,new ReentrantLock(true),公平锁效率比较低
Condition condition = lock.newCondition();// condition必须配合lock一起产生作用
AtomicInteger count = new AtomicInteger();
Runnable comsumer = () -> {
Long id = Thread.currentThread().getId();
while (true) {
lock.lock();
try {
if (count.get() < 1) { // 条件不满足的时候进入等待
System.out.println(id + " comsumer await");
Thread.yield();
condition.await();// 释放锁,并wait,await之后只能等待别的线程notity才能唤醒
continue; // 必须重新进入检测不然会出现超卖
}
System.out.println(id + " comsumer " + (count.getAndDecrement()));
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
Thread.yield();// 为了均衡,让出线程执行
}
}
};
Runnable producer = () -> {
while (true) {
lock.lock();
try {
System.out.println("produce 100");
count.getAndAdd(100);
condition.signalAll(); // 通知其他线程,条件可能满足了,进行唤醒,必须和lock获取锁之后执行,不然会爆IllegalMonitorStateException
} finally {
lock.unlock();
try {
TimeUnit.SECONDS.sleep(5); // 若果在 lock和unlock之间sleep不会释放锁
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
for (int i = 0; i < 10; i++) {
executor.submit(comsumer);
}
executor.submit(producer);// 线程池的 coreSize必须大于这些无限循环的THread,不然也会产生死锁
}
static int num = 0;
public static void condition2() {
Lock lock = new ReentrantLock(true);// 创建非公平锁,效率更高,new ReentrantLock(true),公平锁效率比较低
Condition condition = lock.newCondition();// condition必须配合lock一起产生作用
Runnable comsumer = () -> {
Long id = Thread.currentThread().getId();
while (true) {
lock.lock();
try {
if (num < 1) { // 条件不满足的时候进入等待
System.out.println(id + " comsumer await");
condition.await();// 释放锁,并wait,await之后只能等待别的线程notity才能唤醒
continue; // 必须重新进入检测不然会出现超卖
}
System.out.println(id + " comsumer " + (num--));
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
// Thread.yield();//为了均衡,让出线程执行
}
}
};
Runnable producer = () -> {
while (true) {
lock.lock();
try {
System.out.println("produce 100");
num = 100;
condition.signalAll(); // 通知其他线程,条件可能满足了,进行唤醒,必须和lock获取锁之后执行,不然会爆IllegalMonitorStateException
} finally {
lock.unlock();
try {
TimeUnit.SECONDS.sleep(5); // 若果在 lock和unlock之间sleep不会释放锁
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
for (int i = 0; i < 10; i++) {
executor.submit(comsumer);
}
executor.submit(producer);// 线程池的 coreSize必须大于这些无限循环的THread,不然也会产生死锁
}
public static void lock1() {
Lock lock = new ReentrantLock();
Runnable runnable = () -> {
System.out.println(Thread.currentThread().getId() + " enter");
while (true) {
lock.lock();
System.out.println(Thread.currentThread().getId() + " get lock");
try {
Thread.sleep(200L);
} catch (InterruptedException e) {
e.printStackTrace();
}
lock.unlock();
System.out.println(Thread.currentThread().getId() + " exit ");
}
};
for (int i = 0; i < 100; i++) {
executor.execute(runnable);
}
}
public static void interrupt1() throws InterruptedException {
Runnable r = new Runnable() {
@Override
public void run() {
Thread thread = Thread.currentThread();
while (!thread.isInterrupted()) {
System.out.println("thread running");
}
}
};
Thread rthread = new Thread(r);
rthread.start();
Thread.sleep(1000);
rthread.interrupt();
}
public static void interrupt2() throws InterruptedException {
Runnable r = new Runnable() {
@Override
public void run() {
Thread thread = Thread.currentThread();
while (!Thread.interrupted()) {
System.out.println("thread running");
}
}
};
Thread rthread = new Thread(r);
rthread.start();
Thread.sleep(1000);
rthread.interrupt();
}
public static void future() {
ExecutorService executorService = new ThreadPoolExecutor(10, 1000, 10, TimeUnit.SECONDS,
new ArrayBlockingQueue<>(1000));// Executors.newFixedThreadPool(10);
Callable<String> call = new Callable<String>() {
@Override
public String call() throws Exception {
Thread.sleep(2000);
return "abc";
}
};
FutureTask<String> task = new FutureTask<>(call);
new Thread(task).start();
Future<String> f = executorService.submit(call);
try {
System.out.println(task.get());
System.out.println(f.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
public static void unsafe() {
// jdk.internal.misc.Unsafe.getUnsafe();
Field field;
try {
sun.misc.Unsafe un;
field = Unsafe.class.getField("theUnsafe");
field.setAccessible(true);
Unsafe unsafe = (Unsafe) field.get(null);
unsafe.compareAndSwapInt(unsafe, 0, 0, 0);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
}
}
public static void somaphore() {
Semaphore parkingAdmin = new Semaphore(8);
AtomicInteger waitingCount = new AtomicInteger();
Runnable parkingCar = () -> {
Random random = new Random();
String name = Thread.currentThread().getName();
int count = parkingAdmin.availablePermits();
String msg = "当前有" + count + "个车位,\t" + waitingCount.get() + "辆车在等待,\t" + name
+ ((count > 0) ? "可以进入" : "开始等待");
System.out.println(msg);
try {
waitingCount.incrementAndGet();
parkingAdmin.acquire(1);
waitingCount.decrementAndGet();
Thread.sleep(1000 * (random.nextInt(10) + 5L));
parkingAdmin.release();
count = parkingAdmin.availablePermits();
msg = "当前有" + count + "个车位,\t" + waitingCount.get() + "辆车在等待,\t" + name + "离开停车场";
System.err.println(msg);
} catch (InterruptedException e) {
e.printStackTrace();
}
};
for (int i = 0; i < 40; i++) {
executor.submit(parkingCar);
}
}
public static void countDownLatch() {
CountDownLatch countDownLatch = new CountDownLatch(2);
Runnable countDown = () -> {
try {
Random random = new Random();
Thread.sleep(1000 + random.nextInt(12) * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
countDownLatch.countDown();
System.out.println("countDown");
};
Runnable latch = () -> {
try {
System.out.println("latch waiting");
countDownLatch.await();
System.out.println("latch execute");
} catch (InterruptedException e) {
e.printStackTrace();
}
};
executor.submit(latch);
executor.submit(latch);
executor.submit(latch);
executor.submit(countDown);
executor.submit(countDown);
System.out.println("main waiting");
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("main execute");
// latch waiting
// main waiting
// latch waiting
// latch waiting
// countDown
// countDown
// main execute
// latch execute
// latch execute
// latch execute
}
public static void exchanger() {
// 设计一个讨价还价,随机生成userid,当userid相等退出
Exchanger<User> userExchanger = new Exchanger<>();
AtomicInteger count=new AtomicInteger();
Runnable trade = () -> {
Random random = new Random();
String name = Thread.currentThread().getName();
while (true) {
User user = new User(random.nextInt(30), name);
try {
User newUser = userExchanger.exchange(user);
System.out.println(user + ":" + newUser);
if (user.getId().equals(newUser.getId())) {
System.err.println(count.incrementAndGet()+":=="+user.getName() + "---" + newUser.getName() + "=======trade success");
break;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
for (int i = 0; i < 4; i++) {
executor.submit(trade);
}
}
public static void exchangerTimeOut() {
// 设计一个讨价还价,随机生成userid,当userid相等退出
Exchanger<User> userExchanger = new Exchanger<>();
AtomicInteger count=new AtomicInteger();
Runnable trade = () -> {
Random random = new Random();
String name = Thread.currentThread().getName();
while (true) {
User user = new User(random.nextInt(30), name);
try {
TimeUnit.SECONDS.sleep(random.nextInt(30)*1000);
User newUser = userExchanger.exchange(user,1,TimeUnit.SECONDS);
System.out.println(user + ":" + newUser);
if (user.getId().equals(newUser.getId())) {
System.err.println(count.incrementAndGet()+":=="+user.getName() + "---" + newUser.getName() + "=======trade success");
break;
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
}
};
for (int i = 0; i < 2; i++) {
executor.submit(trade);
}
}
public static void main(String[] args) throws InterruptedException {
exchangerTimeOut();
}
}
java线程大杂烩
最新推荐文章于 2024-07-19 17:37:28 发布