多线程使用

多线程实现方式一:

package cn.luoruiyuan.study.abstractTest;

public class MyThread extends Thread{

	//锁操作共享数据的地方
	static int num=10;
	
	@Override
	public void run() {
		while(true) {
			//锁:任意类都可以,但是所有线程必须一把锁
			synchronized (MyThread.class) {
				if(num>0) {
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println(Thread.currentThread().getName()+":"+num);
					num--;
				}else {
					break;
				}
			}
		}
	}
	
}

多线程实现方式二:

package cn.luoruiyuan.study.abstractTest;

public class MyRunnable implements Runnable{

	//锁操作共享数据的地方
	int num=10;
	
	@Override
	public void run() {
		while(true) {
			//锁:任意类都可以,但是所有线程必须一把锁
			synchronized (MyRunnable.class) {
				if(num>0) {
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println(Thread.currentThread().getName()+":"+num);
					num--;
				}else {
					break;
				}
			}
		}
	}
	
}

多线程调用:

package cn.luoruiyuan.study.abstractTest;

public class ThreadTest {
	
	public void runnableTest() {
		MyRunnable mr=new MyRunnable();
		Thread t=new Thread(mr);
		t.setName("Runnable窗口1");
		t.start();
		Thread t1=new Thread(mr);
		t1.setName("Runnable窗口2");
		t1.start();
		Thread t2=new Thread(mr);
		t2.setName("Runnable窗口3");
		t2.start();
	}
	

	public void threadTest() {
		MyThread mt=new MyThread();
		mt.setName("Thread窗口1");
		mt.start();
		
		MyThread mt1=new MyThread();
		mt1.setName("Thread窗口2");
		mt1.start();
		
		MyThread mt2=new MyThread();
		mt2.setName("Thread窗口3");
		mt2.start();
	}
	
	public static void main(String[] args) {
		ThreadTest tt=new ThreadTest();
		//tt.threadTest();
		tt.runnableTest();
	}
}

Lock锁使用

package cn.luoruiyuan.study.test;

import java.util.concurrent.locks.ReentrantLock;

class Window implements Runnable{

    private int num=10;
    //实例化锁
    private ReentrantLock lock=new ReentrantLock();

    @Override
    public void run() {
        while(true){
            try {
                //加锁
                lock.lock();
                if(num>0){
                    System.out.println(Thread.currentThread().getName()+":"+num);
                    num--;
                }else{
                    break;
                }
            }finally {
                //解锁
                lock.unlock();
            }
        }
    }
}
public class LockTest {
    public static void main(String[] args) {
        Window win=new Window();
        Thread w1=new Thread(win);
        Thread w2=new Thread(win);
        Thread w3=new Thread(win);
        w1.setName("窗口1");
        w2.setName("窗口2");
        w3.setName("窗口3");
        w1.start();
        w2.start();
        w3.start();
    }
}

线程通信,生产者消费者例子

package cn.luoruiyuan.study.test;

/**
 * @author LRY
 * @date 2021/12/3
 */


class Car{
    private int count=0;

    public synchronized void create(){
        if(count<30){
            count++;
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+":创建第"+count+"个车");

            notify();
        }else{
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public synchronized void sell(){
        if(count>0){
            count--;
            try {
                Thread.sleep(101);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+":卖出第"+count+"个车");

            notify();
        }else{
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}

class Production extends Thread{
    private Car car=null;
    public Production(Car car){
        this.car=car;
    }
    @Override
    public void run() {
        while (true){
            car.create();
        }
    }
}

class Consumption extends Thread{
    private Car car=null;
    public Consumption(Car car){
        this.car=car;
    }
    @Override
    public void run() {
        while (true){
            car.sell();
        }
    }
}

public class CommunicationTest {

    public static void main(String[] args) {
        Car c=new Car();
        
        Production p1=new Production(c);
        Consumption c1=new Consumption(c);

        p1.setName("汽车厂家");
        c1.setName("4S店");

        p1.start();
        c1.start();
    }
}

Callable方式实现(可以抛异常,可以接收返回值)


import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;


/**
 * 实现Callable接口
 */
class CallableRun implements Callable {

    @Override
    public Object call() throws Exception {
        Integer num = 0;
        for (int i = 1; i <= 100; i++) {
            num += i;
        }
        return num;
    }

}

/**
 * @author LRY
 * @date 2021/12/6
 */
public class CallableTest {

    public static void main(String[] args) {
        CallableRun cr = new CallableRun();
        FutureTask ft = new FutureTask(cr);
        //启动线程
        Thread t = new Thread(ft);
        t.start();

        try {
            //获取返回值
            Object num = ft.get();
            System.out.printf("Num:" + num);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

    }

}

线程池


import java.util.concurrent.*;

class CallbaleRun implements Callable<Integer>{

    @Override
    public Integer call() throws Exception {
        Integer num=0;
        for(int i=1;i<=100;i++){
            num+=i;
        }
        return num;
    }
}

/**
 * @author LRY
 * @date 2021/12/6
 */
public class CallableTest {

    public static void main(String[] args) {
        //1.提供指定线程数的线程池
        ExecutorService service= Executors.newFixedThreadPool(10);
        System.out.println(service.getClass());

        //2.执行指定线程的操作,需要提供实现Runnable接口或Callable接口实现类的对象
        //service.execute(Runnable runnable);//适用于Runnable
        CallbaleRun cr=new CallbaleRun();
        Future<Integer> fi=service.submit(cr);//适用于Callable
        try {
            Integer num=fi.get();
            System.out.println(num);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        //3.关闭连接池
        service.shutdown();


    }
}








(1)