java练习多线程

1、创建多线程方式继承Thread类

class ThreadDemo1{
    public static void main(String args[]){
        Demo1 d1 = new Demo1();
        d1.start();
        Demo1 d2 = new Demo1();
        d2.start();
    }
}
class Demo1 extends Thread{
    public void run(){
        show();
    }
    public void show(){
        while(true){
            try{Thread.sleep(3000);
            }catch(InterruptedException e){
                
            }
            System.out.println("ол╣Щ"+Thread.currentThread().getName());
        }
    }
}

2、实现多线程第二种方式Runnable接口

class ThreadDemo2{
    public static void main(String[]args){
        Demo d1 = new Demo();
        Thread t1 = new Thread(d1);
        Thread t2 = new Thread(d1);
        Thread t3 = new Thread(d1);
        Thread t4 = new Thread(d1);
        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }
}
class Demo implements Runnable{
    private int sum;
    public void show(){
        for(int x=0;x<20;x++){
            synchronized(this){
                    sum+=100;
                    System.out.println(Thread.currentThread().getName()+"银行金库实时金额:"+sum);
                }
            }
    }
    public void run(){
        show();
    }
}

3、多线程中的同步代码块、同步函数、静态同步函数需要注意的事项

当函数名用static修饰时,同步锁不能用this,static函数的锁使用对象.getClass()获取的字节码文件或者类名.class获取;

class ThreadDemo3{
    public static void main(String[]args){
        Demo d1= new Demo();
        Thread t1 = new Thread(d1);
        Thread t2 = new Thread(d1);
        Thread t3 = new Thread(d1);
        Thread t4 = new Thread(d1);
        t1.start();
        t2.start();
        try{Thread.sleep(10);}catch(InterruptedException e){}
        Demo.flag=false;
        t3.start();
        t4.start();
    }
}
/*
new Thread(d1);任务封装后在Thread类里面的传递过程
class Thread1 implements Runnable{
    Runnable r1;
    Thread1(Runnable r1){
        this.r1=r1;
    }
    public void run(){
        if(r1!=null)
            r1.run();
    }
    public void start(){
        run();
    }
}
*/
class Demo implements Runnable{
    public static boolean flag=true;
    private static int num=300;
    public void run(){
        if(flag){
            while(true)
                method();
        }else{
            synchronized(Demo.class){
                while(true)
                    if(num>0){
                        try{Thread.sleep(30);}catch(InterruptedException e){}
                        System.out.println("同步代码块售票口:"+Thread.currentThread().getName()+"已售出万达电影院门票号:"+num--);    
                    }
            }
        }            
    }
    public synchronized static void method(){
        if(num>0){
                try{Thread.sleep(30);}catch(InterruptedException e){}
                System.out.println("同步函数售票口:"+Thread.currentThread().getName()+"已售出万达电影院门票号:"+num--);    
        }
    }
}
原文地址:https://www.cnblogs.com/wangyinxu/p/6683367.html