Java-多线程并发编程二(完结)
Java多线程并发编程
分成基本内容和原子类等
参考链接:
线程的挂起与恢复(wait、notify、notifyAll)
package Thread;
/**
* @ProjectName: WaitDemo
* @Package: Thread
* @Description:
* @Author: huyuqiao
* @CreateDate: 2020/10/16 10:20
*/
public class WaitDemo implements Runnable{
private static Object object = new Object();
@Override
public void run() {
synchronized (object){
System.out.println(Thread.currentThread().getName() + "占用资源");
try{
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + "释放资源");
}
public static void main(String[] args){
Thread thread = new Thread(new WaitDemo(), "线程A");
thread.start();
Thread thread2 = new Thread(new WaitDemo(), "线程B");
thread2.start();
try{
Thread.sleep(3000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (object){
//object.notify(); //只能唤醒一个
//object.notify();
/*以上2个notify和notfiyall起到一样的效果:只不过前者会顺序释放,后者是自行抢占cpu资源*/
object.notifyAll();
}
}
}
线程中断(Interrupte)
package Thread.Interrupt;
/**
* @ProjectName: Demo
* @Package: Thread.Interrupt
* @Description:
* @Author: huyuqiao
* @CreateDate: 2020/10/16 14:28
*/
public class Demo implements Runnable{
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()){
System.out.println(Thread.currentThread().getName());
}
}
public static void main(String[] args){
Thread thread = new Thread(new Demo());
thread.start();
try{
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
thread.isInterrupted();
}
}
package Thread.Interrupt;
/**
* @ProjectName: PerfectDemo
* @Package: Thread.Interrupt
* @Description:
* @Author: huyuqiao
* @CreateDate: 2020/10/16 14:39
*/
public class PerfectDemo implements Runnable{
private static volatile boolean flag = true;
@Override
public void run() {
while (true){
System.out.println(Thread.currentThread().getName());
}
}
public static void main(String[] args){
Thread thread = new Thread(new PerfectDemo());
thread.start();
try{
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
flag = false;
}
}
线程优先级(priority)
package Thread.Priority;
/**
* @ProjectName: PriorityDemo
* @Package: Thread.Priority
* @Description:
* @Author: huyuqiao
* @CreateDate: 2020/10/16 14:47
*/
public class PriorityDemo{
public static void main(String[] args){
Thread th1 = new Thread(() -> {
while (true){
System.out.println(Thread.currentThread().getName());
}
}, "线程A");
Thread th2 = new Thread(()->{
while (true){
System.out.println(Thread.currentThread().getName());
}
}, "线程B");
th1.setPriority(Thread.MIN_PRIORITY);
th2.setPriority(Thread.MAX_PRIORITY);
th1.start();
th2.start();
}
}
乐观锁、悲观锁、排它锁
package Thread.Priority;
import java.util.concurrent.locks.StampedLock;
/**
* @ProjectName: test
* @Package: Thread.Priority
* @Description:
* @Author: huyuqiao
* @CreateDate: 2020/10/16 15:04
*/
public class StampedLockDemo {
//成员变量
private double x, y;
//锁实例
private final StampedLock sl = new StampedLock();
public static void main(String[] args){
StampedLockDemo stampedLockDemo = new StampedLockDemo();
stampedLockDemo.move(3, 4);
System.out.println(stampedLockDemo.x + " " + stampedLockDemo.y);
}
//排它锁-写锁(writeLock)
void move(double deltaX, double deltaY) {
long stamp = sl.writeLock();
try {
x += deltaX;
y += deltaY;
} finally {
sl.unlockWrite(stamp);
}
}
//乐观读锁
double distanceFromOrigin() {
//尝试获取乐观锁1
long stam = sl.tryOptimisticRead();
//将全部变量拷贝到方法体栈内2
double currentX = x, currentY = y;
//检查在1获取到读锁票据后,锁有没被其他写线程排他性抢占3
if (!sl.validate(stam)) {
//如果被抢占则获取一个共享读锁(悲观获取)4
stam = sl.readLock();
try {
//将全部变量拷贝到方法体栈内5
currentX = x;
currentY = y;
} finally {
//释放共享读锁6
sl.unlockRead(stam);
}
}
//返回计算结果7
return Math.sqrt(currentX * currentX + currentY * currentY);
}
//使用悲观锁获取读锁,并尝试转换为写锁
void moveIfAtOrigin(double newX, double newY) {
//这里可以使用乐观读锁替换1
long stamp = sl.readLock();
try {
//如果当前点远点则移动2
while (x == 0.0 && y == 0.0) {
//尝试将获取的读锁升级为写锁3
long ws = sl.tryConvertToWriteLock(stamp);
//升级成功后,则更新票据,并设置坐标值,然后退出循环4
if (ws != 0L) {
stamp = ws;
x = newX;
y = newY;
break;
} else {
//读锁升级写锁失败则释放读锁,显示获取独占写锁,然后循环重试5
sl.unlockRead(stamp);
stamp = sl.writeLock();
}
}
} finally {
//释放锁6
sl.unlock(stamp);
}
}
}
生产者、消费者
package Thread.ProduceConsumer;
/**
* @ProjectName: Consumer
* @Package: Thread.ProduceConsumer
* @Description:
* @Author: huyuqiao
* @CreateDate: 2020/10/16 15:13
*/
public class Consumer implements Runnable{
private Medium medium;
public Consumer(Medium medium) {
this.medium = medium;
}
@Override
public void run() {
while (true){
medium.take();
}
}
}
package Thread.ProduceConsumer;
/**
* @ProjectName: Medium
* @Package: Thread.ProduceConsumer
* @Description:
* @Author: huyuqiao
* @CreateDate: 2020/10/16 15:15
*/
public class Medium {
private int num = 0;
private static final int TOTAL = 20;
//放数据
public synchronized void put(){
if (num < TOTAL){
System.out.println("新增库存--------当前库存" + ++num);
notifyAll();
} else {
try {
System.out.println("新增库存-----库存已满" + num);
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//拿数据
public synchronized void take(){
if (num > 0) {
System.out.println("减少库存-------当前库存容量" + --num);
notifyAll();
} else {
System.out.println("减少库存--------库存不足" + num);
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
package Thread.ProduceConsumer;
/**
* @ProjectName: Producer
* @Package: Thread.ProduceConsumer
* @Description:
* @Author: huyuqiao
* @CreateDate: 2020/10/16 18:50
*/
public class Producer implements Runnable{
private Medium medium;
public Producer(Medium medium) {
this.medium = medium;
}
@Override
public void run() {
while (true) {
medium.put();
}
}
}
package Thread.ProduceConsumer;
/**
* @ProjectName: Main
* @Package: Thread.ProduceConsumer
* @Description:
* @Author: huyuqiao
* @CreateDate: 2020/10/16 18:51
*/
public class Main {
public static void main(String[] args){
Medium medium = new Medium();
new Thread(new Consumer(medium)).start();
new Thread(new Consumer(medium)).start();
new Thread(new Consumer(medium)).start();
new Thread(new Producer(medium)).start();
new Thread(new Producer(medium)).start();
}
}
Atomic原子类
package Thread.Atomic;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @ProjectName: Demo1
* @Package: Thread.Atomic
* @Description:
* @Author: huyuqiao
* @CreateDate: 2020/10/19 14:31
*/
public class Demo1 {
private static AtomicInteger sum = new AtomicInteger(0);
private static volatile int index;
public static void inCreate(){
sum.incrementAndGet();
}
public static void main(String[] args){
for (int i = 0; i < 10; i++) {
new Thread(() ->{
for (int j = 0; j < 10; j++) {
inCreate();
System.out.println(sum + "+++");
System.out.println(++index + "===");
}
}).start();
}
}
}
我曾七次鄙视自己的灵魂:
第一次,当它本可进取时,却故作谦卑;
第二次,当它在空虚时,用爱欲来填充;
第三次,在困难和容易之间,它选择了容易;
第四次,它犯了错,却借由别人也会犯错来宽慰自己;
第五次,它自由软弱,却把它认为是生命的坚韧;
第六次,当它鄙夷一张丑恶的嘴脸时,却不知那正是自己面具中的一副;
第七次,它侧身于生活的污泥中,虽不甘心,却又畏首畏尾。