多线程基础

多线程基础_第1张图片

 

 

//类锁

package duoxiancheng;
/**
 * 类级别锁   static
 */
/**
 * 一个类创建2个对象      一个对象对象一把锁  相互不冲突   要想实现同步的话  必须在方法上加static
 */
public class MultiThread extends Thread {
    private static int num = 0;
    public   static  synchronized void printNum(String tag) {
        try {
            if (tag.equals("a")) {
                num = 100;
                System.out.println("tag  a  ,set  num  over");
                Thread.sleep(3000);
            } else {
                num = 200;
                System.out.println("tab  b ,set num over");
            }
            System.out.println("tag" + tag + ",num=" + num);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //注意run方法的输出顺序
    public static void main(String[] arg) {
        //创建两个不同的对象
        final MultiThread multiThread1 = new MultiThread();
        final MultiThread multiThread2 = new MultiThread();
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                multiThread1.printNum("a");
            }
        });

        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                multiThread2.printNum("b");
            }
        });
        t1.start();
        t2.start();


    }

}

 

 

同步和异步的区别

多线程基础_第2张图片

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(多线程基础)