线程thread使用

本文深入探讨了Java中的多种并发编程技术,包括使用volatile关键字、原子变量、显式锁、信号量、闭锁、栅栏等高级并发工具进行线程同步的方法。通过具体的代码示例,详细解释了这些工具如何帮助解决并发编程中的常见问题,如死锁、竞争条件和资源争用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

MyRun

package com.lv;

/**
 * Created by LocalUser on 2018/4/24.
 */
public class MyRun implements Runnable{

    private volatile boolean on = true;
    private int i = 0;
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getId() + "线程执行中");

        while (on && !Thread.currentThread().isInterrupted()){
            if(i < 10){

                System.out.println("目前i的值为" + i);
                i++;
            }else {
                Thread.currentThread().interrupt();
            }
        }

    }
}

MyThread

package com.lv;

/**
 * Created by LocalUser on 2018/4/24.
 */
public class MyThread extends Thread{


    private boolean on = true;


    private int i = 0;
    @Override
    public void run() {

        while (on){
            if(i < 10){
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("目前i的值为" + i);
                i++;
            }else {
                on = false;
            }
        }
        System.out.println(Thread.currentThread().getId() + "线程执行中");
    }
}

AtomicTest

package com.lv;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by LocalUser on 2018/5/9.
 */
public class AtomicTest {


    private AtomicInteger atomicInteger = new AtomicInteger();
    public static void main(String[] args){
        AtomicTest atomicTest = new AtomicTest();

        System.out.println(atomicTest.atomicInteger.get());

    }
}

LockTest

package com.lv;

import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * Created by LocalUser on 2018/5/9.
 */
public class LockTest implements Runnable{

    private static int i = 0;

    private ReentrantLock lock = new ReentrantLock();

    private ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
    /*public void increase(){

        lock.lock();
        try{
            i++;
        }finally {
            lock.unlock();
        }

    }*/


    /*public void increase()throws InterruptedException{

        if(lock.tryLock(1, TimeUnit.SECONDS)){
            try{
                i++;
            }finally {
                lock.unlock();
            }
        }else{
            System.out.println("获取锁失败");
        }


    }*/

    public void increase() throws InterruptedException {

        //lock.lockInterruptibly();
        //rwLock.readLock().lockInterruptibly();
        rwLock.writeLock().lockInterruptibly();
        try{
            i++;
        }finally {
            //lock.unlock();
            //rwLock.readLock().unlock();
            rwLock.writeLock().unlock();
        }

    }
    @Override
    public void run() {
        for (int j = 0; j < 10000000; j++) {
            try {
                increase();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args){
        LockTest lockTest = new LockTest();

        Thread t1 = new Thread(lockTest);
        Thread t2 = new Thread(lockTest);


        t1.start();
        t2.start();
        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("i的值为 "+i);
    }
}

CountDownLatchTest

package com.lv;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by LocalUser on 2018/5/16.
 */
public class CountDownLatchTest {

    static int num = 10;
    static CountDownLatch countDownLatch = new CountDownLatch(num);
    static AtomicInteger result = new AtomicInteger(0);
    static Random random=new Random();


    static class Parse implements Runnable{
        @Override
        public void run() {
            int sum=0;
            for(int i=1;i<100;i++){
                sum+=random.nextInt(i);
            }

            result.addAndGet(sum);
            countDownLatch.countDown();
            System.out.println(Thread.currentThread().getId() + " 解析完一个sheet,结果为 " + sum);
        }
    }

    public static void main(String[] args){
        for (int i = 0; i < num; i++) {
            new Thread(new Parse()).start();
        }

        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("所有sheet解析完毕,最终结果" + result);
    }
}

CyclicBarrierTest

package com.lv;

import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by LocalUser on 2018/5/16.
 */
public class CyclicBarrierTest {


    static int num = 10;
    static CyclicBarrier cyclicBarrier = new CyclicBarrier(num,new Aculate());
    static AtomicInteger result = new AtomicInteger(0);
    static Random random=new Random();


    static class Parse implements Runnable{
        @Override
        public void run() {
            int sum=0;
            int seed = Math.abs(random.nextInt());
            for(int i=1;i<100;i++){
                sum+=random.nextInt(seed);
            }

            result.addAndGet(sum);
            System.out.println(System.currentTimeMillis() + " 解析完一个sheet,结果为 " + sum);

            try {
                cyclicBarrier.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }

            System.out.println(System.currentTimeMillis() + " 越过屏障");
        }
    }


    static class Aculate implements Runnable{
        @Override
        public void run() {
            System.out.println("所有sheet解析完毕,最终结果" + result);
        }
    }
    public static void main(String[] args){
        for (int i = 0; i < num; i++) {
            new Thread(new Parse()).start();
        }




    }
}

SemaphoreTest

package com.lv;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;


/**
 * Created by LocalUser on 2018/5/16.
 */
public class SemaphoreTest {


    static int num = 30;
    static Semaphore semaphore = new Semaphore(10);
    static Random random = new Random();
    static ExecutorService threadPool = Executors.newFixedThreadPool(num);


    public static void main(String[] args){


        for (int i = 0; i < num; i++) {
            threadPool.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        semaphore.acquire();

                        int sum = 0;
                        for (int i = 1; i < 100; i++) {
                            sum += random.nextInt(i);

                        }
                        System.out.println(Thread.currentThread().getId() + " 执行完save data 结果为 " + sum);

                        Thread.sleep(2000);
                        semaphore.release();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
        threadPool.shutdown();
    }

}

ProCus

package com.lv;

import java.util.PriorityQueue;

/**
 * Created by LocalUser on 2018/5/16.
 */
public class ProCus {

    private int queueSize = 10;
    private PriorityQueue<Integer> queue = new PriorityQueue<Integer>(queueSize);



    class Producer extends Thread{
        public void run(){

            produce();
        }

        public void produce()  {
            while(true){
                synchronized (queue){
                    while(queue.size() == queueSize){
                        System.out.println("queue的大小满了!等待消费者消费");
                        try {
                            queue.notify();
                            queue.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

                    queue.offer(1);
                    System.out.println("生产一个包子,总共" + queue.size());


                }
            }
        }
    }


    class Consumer extends Thread{
        public void run(){

            consume();

        }

        public void consume() {
            while(true){
                synchronized (queue){
                    while(queue.isEmpty()){
                        System.out.println("queue的大小为空!等待生产者生产");
                        try {
                            queue.notify();
                            queue.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

                    queue.poll();
                    System.out.println("消费了一个包子,还剩" + queue.size());

                }
            }
        }
    }

    public static void main(String[] args){
        ProCus proCus = new ProCus();

        Producer producer = proCus.new Producer();
        Consumer consumer = proCus.new Consumer();


        consumer.start();

        producer.start();
    }
}

ProCusCondition

package com.lv;

import java.util.PriorityQueue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by LocalUser on 2018/5/16.
 */
public class ProCusCondition {

    private int queueSize = 10;
    private PriorityQueue<Integer> queue = new PriorityQueue<Integer>(queueSize);
    private ReentrantLock lock = new ReentrantLock();
    private Condition empty = lock.newCondition();
    private Condition full = lock.newCondition();


    class Producer extends Thread{
        public void run(){

            produce();
        }

        public void produce()  {
            while(true){
                lock.lock();
                try{
                    while(queue.size() == queueSize){
                        System.out.println("queue的大小满了!等待消费者消费");
                        try {
                            empty.signal();
                            full.await();

                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

                    queue.offer(1);
                    System.out.println("生产一个包子,总共" + queue.size());


                }finally {
                   lock.unlock();
                }
            }
        }
    }


    class Consumer extends Thread{
        public void run(){

            consume();

        }

        public void consume() {
            while(true){
                lock.lock();
                try{
                    while(queue.isEmpty()){
                        System.out.println("queue的大小为空!等待生产者生产");
                        try {
                            full.signal();
                            empty.await();

                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

                    queue.poll();
                    System.out.println("消费了一个包子,还剩" + queue.size());


                }finally {
                    lock.unlock();
                }
            }
        }
    }

    public static void main(String[] args){
        ProCusCondition proCus = new ProCusCondition();

        Producer producer = proCus.new Producer();
        Consumer consumer = proCus.new Consumer();


        consumer.start();

        producer.start();
    }
}

User

package com.lv;

/**
 * Created by LocalUser on 2018/4/24.
 */
public class User extends Thread{

    public static final String CITY = "ShenZhen";
    private int age;
    private String address;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public User(int age, String address) {
        this.age = age;
        this.address = address;
    }

    public synchronized void waitAge() {
        while (30 > age){
            try {
                System.out.println("当前线程waitAge" + Thread.currentThread().getId() + " is wait");
                wait();
                System.out.println("当前线程waitAge" + Thread.currentThread().getId() + " is notified");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println("当前user的age" + age);

    }

    public synchronized void waitAddress() {

        while (CITY.equals(address)){
            try {
                System.out.println("当前线程waitAddress" + Thread.currentThread().getId() + " is wait");
                wait();
                System.out.println("当前线程waitAddress" + Thread.currentThread().getId() + " is notified");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println("当前user的address" + address);

    }

    public synchronized void notifyAddress() {

        notifyAll();

    }

    public synchronized void notifyAge() {

        notifyAll();
    }
}

Test

package com.lv;

/**
 * Created by LocalUser on 2018/5/9.
 */
public class Test {

    private static User user = new User(29,User.CITY);

    static class CheckAge extends Thread{
        public void run(){
            user.waitAge();
        }
    }

    static class CheckAddress extends Thread{
        public void run(){
            user.waitAddress();
        }
    }


    public static void main(String[] args){

        for (int i = 0; i < 3; i++) {
            CheckAge checkAge = new CheckAge();
            checkAge.start();
        }

        for (int i = 0; i < 3; i++) {
            CheckAddress checkAddress = new CheckAddress();
            checkAddress.start();
        }

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


        user.setAddress("NewYork");
        user.notifyAddress();
    }
}

SyncTest

package com.lv;

/**
 * Created by LocalUser on 2018/5/15.
 */
public class SyncTest implements Runnable{


    private static int i = 0;

    /*public synchronized void increase(){
        i++;
    }*/

    /*public static synchronized void increase(){
        i++;
    }*/

    /*public void increase(){
        synchronized (this){
            i++;
        }

    }*/

    public void increase(){
        synchronized (SyncTest.class){
            i++;
        }

    }
    @Override
    public void run() {
        for (int j = 0; j < 10000000; j++) {
            increase();
        }
    }

    public static void main(String[] args){
        SyncTest syncTest = new SyncTest();

        /*Thread t1 = new Thread(syncTest);
        Thread t2 = new Thread(syncTest);*/

        Thread t1 = new Thread(new SyncTest());
        Thread t2 = new Thread(new SyncTest());

        t1.start();
        t2.start();
        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("i的值为 "+i);
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值