多线程

notify()和notifyAll()的区别的睿智回答

多线程_第1张图片
image.png

继承Thread创建线程

public class MyThread extends Thread{
    private String name;
    public MyThread(String name){
        this.name=name;
    }
    @Override
    public void run(){
        while (true){
            System.out.println("The Thread Name is:"+name);
        }
    }
    public static void main(String[] args) {
        MyThread m1=new MyThread("AS");
        MyThread m2=new MyThread("sad");
        m1.start();
        m2.start();
    }
}
多线程_第2张图片
image.png

加上sleep

public class MyThread extends Thread{
    private String name;
    public MyThread(String name){
        this.name=name;
    }
    @Override
    public void run(){
        while (true){
            try{
                sleep(1000);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
            System.out.println("The Thread Name is:"+name);
        }
    }
    public static void main(String[] args) {
        MyThread m1=new MyThread("AS");
        MyThread m2=new MyThread("sad");
        m1.start();
        m2.start();
    }
}
多线程_第3张图片
image.png

实现Runnable接口

import static java.lang.Thread.sleep;

public class MyThread implements Runnable{
    private static int count=0;
    @Override
    public void run(){
        while (true){
            try{
                count++;
                sleep(100);
                System.out.println("The Counter is:"+count);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
    }
    public static void main(String[] args) {
        MyThread m=new MyThread();
        Thread t1=new Thread(m);
        Thread t2=new Thread(m);
        t1.start();
        t2.start();
        
    }
}
多线程_第4张图片
image.png

方法同步


import static java.lang.Thread.sleep;

public class MyThread implements Runnable{
    private static int count=0;
    @Override
    public void run(){
        while (true){
            try{
                synchronized(this){
                    count++;
                    sleep(100);
                    System.out.println("The Counter is:"+count);
                }
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
    }
    public static void main(String[] args) {
        MyThread m=new MyThread();
        Thread t1=new Thread(m);
        Thread t2=new Thread(m);
        t1.start();
        t2.start();
    }
}
多线程_第5张图片
image.png

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