자바 멀티 스레딩 생성 및 적용

자바에서 여러 스레드를 만드는 두 가지 방법

1 : Estends Thread 클래스

public class hacker_01_MyThread extends Thread  {

    public hacker_01_MyThread(String name) {
        super(name);
    }

    @Override
    public void run() {
        System.out.println(this.getName()+"正在执行。。。");
        try {
            Thread.sleep(3000);
} catch (InterruptedException e) {
        e.printStackTrace();
        }

        System.out.println(this.getName()+"执行完成。。。");
        }

}

이전

public class hacker_02_MyThreadDemo {

    public static void main(String[] args) {

        for (int i=0;i<100;i++)
        {

            hacker_01_MyThread thread = new hacker_01_MyThread("线程" + i);
            thread.start();
        }


        System.out.println("主线程结束。。。");

    }
}

 

2 : 새 스레드 (실행 가능한 인터페이스 구현 클래스)

두 번째로 가장 일반적으로 사용되는 메서드 인 클래스는 여러 인터페이스를 구현할 수 있으며 클래스는 하나의 부모 클래스에서만 상속 할 수 있습니다.

 

public class hacker_03_RunableImpl1 implements Runnable{

    @Override
    public void run() {
            System.out.println("线程执行")
            }

}

이전

public class hacker_03_RunableImpleDemo {
    public static void main(String[] args) {

        // Runable接口的实现类
        hacker_03_RunableImpl1 hacker_03_runable1 = new hacker_03_RunableImpl1();
    
        for(int i=0;i<3300;i++){
            new Thread(hacker_03_runable1).start();


        }
        System.out.println("主线程结束。。。");
    }

}

 

Runnable 인터페이스를 구현하는 구현 개체는 여러 번 시작될 때 실행할 여러 스레드를 만들어 구성원 변수를 공유하여 스레드 불안정을 유발합니다.

솔루션 : 동기화 코드 블록, 동기화 방법, 잠금 개체

public class hacker_03_RunableImpl1 implements Runnable{

    private  int ticket=100;
    //锁对象
    private  Object obj=new Object();

    @Override
    public void run() {
        // 第一种保证同步,synchronized同步代码块
        synchronized(obj){

            if (ticket >0){
            --ticket;
            System.out.println("现在正在卖"+ticket+"张");
            }

        }


    }
}

 

public class hacker_03_RunableImpl2 implements Runnable {
    private int ticket=10000;

    @Override
    public void run() {
        SaleTicket();
    }
    // 第二种保证同步,同步方法
    private  /*synchronized*/ void SaleTicket(){
        if(this.ticket>0){
            System.out.println("现在正在卖第"+ticket);
            this.ticket=--this.ticket;
        }
    }

}
public class hacker_03_RunableImpl3 implements Runnable{

    private int ticket=10000;

    // 多态
    private Lock I =new ReentrantLock();


    @Override
    public void run() {
        // 第三种保证同步,锁对象
//        I.lock();
        System.out.println("现在正在卖第"+ticket+"张票");
        --ticket;
//        I.unlock();
    }


}

 

 

추천

출처blog.csdn.net/Growing_hacker/article/details/108882114