首页 > 代码库 > 多线程的一些小Demo

多线程的一些小Demo

一、多个线程单个锁

package com.sun.multithread.sync;

public class MyThread extends Thread {

    private int count = 5;
    
    // synchronized加锁
    public synchronized void run() {
        count--;
        System.out.println(this.currentThread().getName() + " count = " + count);
    }
    
    public static void main(String[] args) {
        
        MyThread myThread = new MyThread();
        Thread t1 = new Thread(myThread, "t1");
        Thread t2 = new Thread(myThread, "t2");
        Thread t3 = new Thread(myThread, "t3");
        Thread t4 = new Thread(myThread, "t4");
        Thread t5 = new Thread(myThread, "t5");
        
        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t5.start();
    }
}

二、多个线程多把锁

package com.sun.multithread.sync;

public class MultiThread {
    
    private static int num = 0;
    
    /**
     * 在静态方法上加synchronized关键字,表示锁定class类,类级别的锁
     * 关键字synchronized取得的锁都是对象锁,而不是把一段代码(方法)当成锁,
     * 所以代码中哪个线程先执行synchronized关键字的方法,哪个线程就持有该方法所属对象的锁
     * 
     * @param tag 参数
     */
    public static synchronized void printNum(String tag){
        try {
            if(tag.equals("a")){
                num = 100;
                System.out.println("tag a, set num over!");
                Thread.sleep(1000);
            } else {
                num = 200;
                System.out.println("tag b, set num over!");
            }
            System.out.println("tag " + tag + ", num = " + num);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    
    public static void main(String[] args) {
        // 两个不同的对象
        final MultiThread m1 = new MultiThread();
        final MultiThread m2 = new MultiThread();
        
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                m1.printNum("a");
            }
        });
        
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                m1.printNum("b");
            }
        });
        
        t1.start();
        t2.start();
    }
}

 

多线程的一些小Demo