java多线程与并发(基础篇)
发布日期:2021-05-09 09:32:50 浏览次数:19 分类:博客文章

本文共 31633 字,大约阅读时间需要 105 分钟。

���������������������

������������������������������������������������������������������������������������������������������������������

������������������������������������������������������������������������������������������������������������������������ ���������

���������������������������������������������CPU������������������������������������������������������CPU������������������������

���������������

������������������������������������������������������������������������������������������������������������������������������������������������

 

 ������������������������������������������������������������������������������������������ ���

������������������������������������������������������������������������������������������������������������������������������������������

���������������������������������������������������������������������������������������������

��������������������������� NM ��������������������������������������������������������������������� ���

 

���������������

������������������������������������������������������������������������������������������������������������������

������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������

 

1) ������������,���������������������������������,���������������������������������.

2) ���������������������������������������������������������������������������

3) ���������������������������������������������������������������������������������������������������������������������������������������������

4) ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������

5) ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������

 

���������������������

��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������� ���

������������������������������������������������������������ ���

���������������������������������������������������������CPU������������������������������������������������������������������������������������

 

���������������������������������

1������������������������

������������������������������������1���������������������1������������������1������������������������������������������������������������������������������������������������������������������������

 

2���������������������������������

Java������������������������������������

Java ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������� ������������������������

������������������java���������������

������������������������������ CPU ���������������������������������������������������������������������������������������������������������������������������������������������������������CPU���������������������������������������������������������������������������������CPU��������������������������� ������Java������������������������������������������������������ Ll������ L2 ������������ CPU ������������

1���������A������������������������X���������������������Cache������������������������������������������X������������������0������������X=0������������������������������������A������X���������1,������������������������Cache������������������������������������A������������������������A���������CPU���������Cache������������������������X������������l���

2���������B������X������������������������������������������������������������������������������������������������������X=1���������������������������������������������������������������������X=l���������������B������X���������2���������������������������2���������������Cache���������������Cache������������������������������X���������2���������������������������������

3���������A���������������������X���������������������������������������������X=l���������������������������������������B���������X���������������2���������������A���������������l���������������������������������������������������������������������B���������������������A������������

 

synchronized ������������������

���������������������������������������������������������������������������synchronized���������������������������synchronized���������������������������������������������������������������������synchronized������������������������������������������������������������������������������������������������������������������synchronized���������������������������synchronized������������������������������������������������������������������������������������������������������������������

 

Volatile������������

���������������������������������������������������������������������������������������������������������volatile���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������volatile������������������synchronized���������������������������������������������������������volatile������������������������������������synchronized���������������������������������������������������������������������������volatile������������������������������������������������������������������������������������������������������������������������������������

 

������������������

1���������Thread���

������run���������������������������������������������run���������������������������������������������this���������������������������Thread.currentThread���������������������������������Java������������������������������������Thread������������������������������������������������������������������������������������������������������������������������������������������������

public class ThreadRuning extends Thread{    public ThreadRuning(String name){  //������������������������������������������        super(name);    }    @Override    public void run() {        while(true){            System.out.println("good time");//���run������������this������������������            System.out.println(this);        }    }    public static void main(String[] args){        ThreadRuning threadRuning = new ThreadRuning("1111");        threadRuning.start();    }}

2���������Runable������

������run���������������������Thread���������������������������

public class RunableTest implements Runnable {    @Override    public void run() {        while (true) {            System.out.println("good time");        }    }    public static void main(String[] args) {        RunableTest runableTest1 = new RunableTest();        RunableTest runableTest2 = new RunableTest();        new Thread(runableTest1).start();        new Thread(runableTest1).start();        new Thread(runableTest2).start();    }}

3���������Callable������

������call���������

public class CallTest implements Callable {    @Override    public Object call() throws Exception {        return "hello world";    }    public static void main(String[] args){        FutureTask
futureTask = new FutureTask
(new CallTest()); new Thread(futureTask).start(); try { String result = futureTask.get(); System.out.println(result); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } }}

���������������������������������������������������������������������������������������������������set������������������������������������������������������������������������Runnable���������������������������������������������������final������������������������������Java������������������������������������Thread������������������������������������������������Runable���������������������������������������������������������������������������������������Callable������������

 

������Thread���������

���������������

1���������������������������������������������������������������

2������������������������������name���������������Thread-������������������������

3������������������������������.���������������������������������������������������. 1-10������������5

4���main���������������������main������������������������������������������������������������������������������������������

5������������������run()���������������������������������������������������������,������������������������������������������������������.

6������������������������������������������,���������������������������������������.

7������JVM���������,������������������������������������������(������������������������������������main()������)

JVM������������������������������������������������������������:

1���������������exit()��������������� ��� ���������������������exit()���������������.

2������������������������������������������������,or run()������������������or���run()������������������������������������������������.

 

Init���������

/** * Initializes a Thread. * @param g ��������� * @param target ������������ * @param name ��������� * @param stackSize ������������������������0������������ * @param acc������������������������������������ * @param inheritThreadLocals������������true,������������������������������������������������������������*/private void init(ThreadGroup g, Runnable target, String name,                  long stackSize, AccessControlContext acc,                  boolean inheritThreadLocals) {    if (name == null) {        throw new NullPointerException("name cannot be null");    }    this.name = name;    Thread parent = currentThread();    SecurityManager security = System.getSecurityManager();   //������������������������null if (g == null) {        /* Determine if it's an applet or not */        /* If there is a security manager, ask the security manager   //���������������������,������������������������������������           what to do. */        if (security != null) {            g = security.getThreadGroup();        }        /* If the security doesn't have a strong opinion of the matter           use the parent thread group. *///������������������������������������������������������������������������������������        if (g == null) {            g = parent.getThreadGroup();        }    }    /* checkAccess regardless of whether or not threadgroup is       explicitly passed in. *///���������������������������������������,������������������������.    g.checkAccess();    /*     * Do we have the required permissions?     */    if (security != null) {        if (isCCLOverridden(getClass())) {            security.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);        }    }    g.addUnstarted();    this.group = g;    this.daemon = parent.isDaemon();//������������������������������,������������������ ���������������������.    this.priority = parent.getPriority();//���������������������������    if (security == null || isCCLOverridden(parent.getClass()))        this.contextClassLoader = parent.getContextClassLoader();    else        this.contextClassLoader = parent.contextClassLoader;    this.inheritedAccessControlContext =            acc != null ? acc : AccessController.getContext();    this.target = target;    setPriority(priority);    if (inheritThreadLocals && parent.inheritableThreadLocals != null)        this.inheritableThreadLocals =            ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);    /* Stash the specified stack size in case the VM cares */    this.stackSize = stackSize;    /* Set thread ID ������������id*/    tid = nextThreadID();}

������

������������������������������������������������init()������

public Thread() {    init(null, null, "Thread-" + nextThreadNum(), 0);}public Thread(Runnable target) {    init(null, target, "Thread-" + nextThreadNum(), 0);}public Thread(Runnable target, AccessControlContext acc) {    init(null, target, "Thread-" + nextThreadNum(), 0, acc, false);}public Thread(ThreadGroup group, Runnable target) {    init(group, target, "Thread-" + nextThreadNum(), 0);}public Thread(String name) {    init(null, null, name, 0);}public Thread(ThreadGroup group, String name) {    init(group, null, name, 0);}public Thread(Runnable target, String name) {    init(null, target, name, 0);}public Thread(ThreadGroup group, Runnable target, String name,              long stackSize) {    init(group, target, name, stackSize);}

 ���������������

public enum State {        NEW,        RUNNABLE,        BLOCKED,        WAITING,        TIMED_WAITING,        TERMINATED;    }

������

NEW������������������������������, ������������

RUNNABLE���������������������������������������, ������������������������������������/IO���������������/CPU������������������, ���������������������������������������������������������, ������������, Sleep���

BLOCKED������������������, ������������������������������������������, ������������������������������������synchronized ������������������, ������������������ synchronized������������������wait() ������, ������������������������������������������������

WAITING������������������������������������������������������, ���������������wait������, ������������������/������������������ notify / notifyAll ������������������������������������������, ��������������� BLOCKED ��� WATING ���������, ���������������������������������������, ���������������������������wait������������notify, ���������������join������ join���������������������������, ������������WAITING������, ������������join���������������������

TIMED_WAITING������������������������������(������������)���WAITING, ���������������������wait(long), join(long)������������, ������������������sleep���, ������������TIMED_WAITING������

TERMINATED��� ��������������������� ������������run���������������������������, ���������������������������(���������������������������������, ���������������������)

������������������������������running���������������������������������������������������������������������������while���������������������������������������jconsole������������������������������������������Runable���������

Api������������������������

���������������������������������������������������running���������������������������������runable������������������������������������������������������������������������������������������������������

 

Start���������

public synchronized void start() {        /**         * ���������������������������������������or���������������������������������������������.         * ���������������������������������������������������������������������������������.         * 0������������������NEW���������.         */        if (threadStatus != 0) // ������������������start            throw new IllegalThreadStateException();        /* Notify the group that this thread is about to be started         * so that it can be added to the group's list of threads         * and the group's unstarted count can be decremented. */        group.add(this);        boolean started = false;        try {            start0(); //������������            started = true;        } finally {            try {                if (!started) {                    group.threadStartFailed(this);                }            } catch (Throwable ignore) {                /* do nothing. If start0 threw a Throwable then                  it will be passed up the call stack */            }        }    }    private native void start0();

yield������:

public static native void yield();

������������������������������������������������������������������������������CPU������������������������������������������������������������������������������������������������������������RUNNABLE,������������������������RUNNABLE���RUNNING���������

sleep���������

/**     * ������������������������������������sleep(������������������)���������������.     * ���������������������������������������������������������������(monitor)������������(ownership).     */public static native void sleep(long millis) throws InterruptedException;public static void sleep(long millis, int nanos)throws InterruptedException {    if (millis < 0) {        throw new IllegalArgumentException("timeout value is negative");    }    if (nanos < 0 || nanos > 999999) {        throw new IllegalArgumentException(                            "nanosecond timeout value out of range");    }    if (nanos >= 500000 || (nanos != 0 && millis == 0)) {        millis++;    }    sleep(millis);}

������sleep���������������������������������sleep���������������cpu���������������������������������������������sleep()���������RUNNABLE������������TIMED_WAITING������

join������ 

/**     * ������������������millis(ms)������������������������������.���������0���������������������.     * ���������������������:���������������this.isAlive()������������������wait()������.     * ������������������notifyAll()������������������.     * ������������������������������������������������wait,notify,notifyAll������.     */    public final synchronized void join(long millis)            throws InterruptedException {        long base = System.currentTimeMillis();        long now = 0;        //������������������<0,���������������        if (millis < 0) {            throw new IllegalArgumentException("timeout value is negative");        }        //���������������������0        if (millis == 0) {            while (isAlive()) {                wait(0);            }        } else {            while (isAlive()) {                long delay = millis - now;                if (delay <= 0) {                    break;                }                wait(delay);                now = System.currentTimeMillis() - base;            }        }    }    //���������������������������,������������������������������������    public final synchronized void join(long millis, int nanos)            throws InterruptedException {        if (millis < 0) {            throw new IllegalArgumentException("timeout value is negative");        }        if (nanos < 0 || nanos > 999999) {            throw new IllegalArgumentException(                    "nanosecond timeout value out of range");        }        if (nanos >= 500000 || (nanos != 0 && millis == 0)) {            millis++;        }        join(millis);    }    //������������:���������������������������.    public final void join() throws InterruptedException {        join(0);    }

������join������������A������������������B���������������������������A���������������������������������������������������������B������BLOCKED���������������������������A

 

������������������

������������������Object������wait���notify���notifyAll������

wait������

public final native void wait(long timeout) throws InterruptedException; //������������ ���������������public final void wait(long timeout, int nanos) throws InterruptedException {//������������������������        if (timeout < 0) {            throw new IllegalArgumentException("timeout value is negative");        }        if (nanos < 0 || nanos > 999999) {            throw new IllegalArgumentException(                                "nanosecond timeout value out of range");        }        if (nanos > 0) {            timeout++;        }        wait(timeout);    }    public final void wait() throws InterruptedException {        wait(0);    }

������

������wait()���wait(long timeout, int nanos)������������������������wait(long timeout)���������

���������������������wait(long timeout)������
wait���������������������������������������������������������������������������������������notify������notifyAll()���������������������������������������������������������
������wait������������������������������������������������������������
wait������������������������T������������������object������������������������������������������������������������������������������������������������������������������������T������������������������������������������T���������������������T������������������������wait������������������������

1������������������������������������������������notify������������������������������������������������������������������������������������������������

2������������������������������������������notifyAll������
3���������������������������interrupt���������������������T
4���������������������������������wait���������������������������������timeout���������0������������������������������������0���������������������������������������������������������������

������������������T���������������������������������������������������������������������������������������������������T������������������������������������������������������������������������������T���������������������������������������������������������������������������������������������������������������������������wait������������������������������������T���wait������������������������������������������wait���������������������������������������������T������������wait���������������������������������
������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������wait������������������������������������������������������

synchronized(������){    while(���������������){     ������.wait();  }  ���������������������}

    ������������������������������������������������������������������������������������������������interrupt()���������������������������InterruptedExcaption���������������������������������������������������������������������������������������������������������������������
     ������������������wait������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������
    ������������������������������������������������������������������
    wait(long timeout, int nanos)������������������������nanos������0���������timeout���������������������������������������������������������������������������wait(long timeout)������

notify������

public final native void notify(); //������������

������������������������������������������������������������JVM(������������������)������������������������wait������������������

 ���������notify()������������������������������������������������������
 ���������notify()���������������������������������������������������synchronized���������������������������������������
 notify()���������������������������������������������

notifyAll()������

public final native void notifyAll();//������������

���notify()���������������������������������������������������������������������������������������������������������������������������������������

������������������������������������������������������������������������������
������������������������������������������������������������
- ���������������������������������������������
- ���������������������������������������

������������

1���sleep

public class ThreadDemo1 {    public static void main(String[] args) {        MyThread mt = new MyThread();        //������        MyRunnable mr = new MyRunnable();        Thread t2 = new Thread(mr);        mt.start();//������������        t2.start();        for (int i = 0; i < 100; i++) {            System.out.println(Thread.currentThread().getName() + "-" + i);            try {                Thread.sleep(500);            } catch (InterruptedException e) {                e.printStackTrace();            }        }    }}/** * ���������������������������������������thread��� */class MyThread extends Thread {    @Override    public void run() {        for (int i = 0; i < 100; i++) {            if (this.isInterrupted()) {                break;            }            System.out.println(Thread.currentThread().getName() + "-" + i);            try {                Thread.sleep(500);            } catch (InterruptedException e) {                e.printStackTrace();                this.interrupt();            }        }    }}/** * ���������������������������������������Runnable������ */class MyRunnable implements Runnable {    @Override    public void run() {        for (int i = 0; i < 100; i++) {            System.out.println(Thread.currentThread().getName() + "-" + i);            try {                Thread.sleep(500);            } catch (InterruptedException e) {                e.printStackTrace();            }        }    }}

���2���join������������������������������������

public class ThreadDemo2 {    public static void main(String[] args){        MyRunable2 mr2 = new MyRunable2();        Thread t = new Thread(mr2);//        t.start();        MyRunable3 mr3 = new MyRunable3();        Thread t2 = new Thread(mr3);        t2.start();        for (int i = 0; i < 50; i++) {            System.out.println(Thread.currentThread().getName()+"--"+i);            try {                Thread.sleep(300);            } catch (InterruptedException e) {                e.printStackTrace();            }            if(i==20){//                try {  //������������������������join//                    t.join();//���t������������������//                } catch (InterruptedException e) {//                    e.printStackTrace();//                }//                t.interrupt();//������������,���������������������������������������������interrupt������                mr3.flag = false; //������������������������            }        }    }}class MyRunable2 implements Runnable{    @Override    public void run() {        for (int i = 0; i < 50; i++) {            if(Thread.interrupted()){//������������������������������������������������������                //....                break;            }            System.out.println(Thread.currentThread().getName()+"--"+i);            try {                Thread.sleep(300);            } catch (InterruptedException e) {                e.printStackTrace();                Thread.currentThread().interrupt();            }        }    }} //������������class MyRunable3 implements Runnable{    public boolean flag = true;    public MyRunable3(){        flag = true;    }    @Override    public void run() {        int i=0;        while(flag){            System.out.println(Thread.currentThread().getName()+"==="+(i++));            try {                Thread.sleep(300);            } catch (InterruptedException e) {                e.printStackTrace();            }        }    }}

���3���������������������������

public class ThreadDemo3 {    public static void main(String[] args){        MyRunnable4 mr4 = new MyRunnable4();        Thread t = new Thread(mr4);        t.setName("Thread-t");        //���������������������������������������CPU���������������������        t.setPriority(Thread.MAX_PRIORITY);        //��������������������������������� ���������������������������������������������������JVM���������        t.setDaemon(true);//������������������������������        System.out.println(t.isAlive());        t.start();        System.out.println(t.isAlive());        for (int i = 0; i < 50; i++) {            System.out.println("main--"+i);            try {                Thread.sleep(200);            } catch (InterruptedException e) {                e.printStackTrace();            }            if (i==5){                Thread.yield();//������������CPU���������������            }        }    }}class MyRunnable4 implements Runnable{    @Override    public void run() {        for (int i = 0; i < 50; i++) {            System.out.println("--"+i);            try {                Thread.sleep(500);            } catch (InterruptedException e) {                e.printStackTrace();            }        }    }}

4���������������������������������������������������������������������������

���������������������

package threadtest.procon;public interface AbstractStorage {    void consume(int num);    void product(int num);}

���������������������������������������������������������

package threadtest.procon;import java.util.LinkedList;/** * @author: LUGH1 * @date: 2019-7-4 * @description: */public class Storage implements AbstractStorage{    private final int MAX_SIZE = 100;    private LinkedList list = new LinkedList();    @Override    public void consume(int num) {        synchronized (list){            while (list.size()
MAX_SIZE){ System.out.println("������������������������������:" + num + "\t���������������:" + list.size() + "\t������������������������������!"); try { list.wait(2000); } catch (InterruptedException e) { e.printStackTrace(); } } for(int i=0;i

������

���

���������������

package threadtest.procon;/** * @author: LUGH1 * @date: 2019-7-4 * @description: */public class Producer extends Thread {    private int num;    public AbstractStorage abstractStorage;    public Producer(AbstractStorage abstractStorage){        this.abstractStorage = abstractStorage;    }    public void setNum(int num) {        this.num = num;    }    public void produce(int num){        abstractStorage.product(num);    }    @Override    public void run() {        produce(num);    }}

���������������������

package threadtest.procon;/** * @author: LUGH1 * @date: 2019-7-4 * @description: */public class Consumer extends Thread {    private int num;    public AbstractStorage abstractStorage;    public Consumer(AbstractStorage abstractStorage){        this.abstractStorage = abstractStorage;    }    public void setNum(int num){        this.num = num;    }    public void consume(int num){        this.abstractStorage.consume(num);    }    @Override    public void run() {        consume(num);    }}

���������������

package threadtest.procon;/** * @author: LUGH1 * @date: 2019-7-4 * @description: */public class Test {    public static void main(String[] args){        AbstractStorage abstractStorage = new Storage();        // ���������������        Producer p1 = new Producer(abstractStorage);        Producer p2 = new Producer(abstractStorage);        Producer p3 = new Producer(abstractStorage);        Producer p4 = new Producer(abstractStorage);        Producer p5 = new Producer(abstractStorage);        Producer p6 = new Producer(abstractStorage);        Producer p7 = new Producer(abstractStorage);        // ���������������        Consumer c1 = new Consumer(abstractStorage);        Consumer c2 = new Consumer(abstractStorage);        Consumer c3 = new Consumer(abstractStorage);        // ���������������������������������        p1.setNum(10);        p2.setNum(20);        p3.setNum(30);        p4.setNum(40);        p5.setNum(30);        p6.setNum(20);        p7.setNum(80);        // ���������������������������������        c1.setNum(50);        c2.setNum(70);        c3.setNum(20);        c1.start();        c2.start();        c3.start();        p1.start();        p2.start();        p3.start();        p4.start();        p5.start();        p6.start();        p7.start();    }}

������

 

������

���java������������������

���java���������������������

 

上一篇:linux之压缩和解压
下一篇:linux下实现并发逻辑

发表评论

最新留言

很好
[***.229.124.182]2025年04月11日 10时12分47秒