多线程

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

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();
    }
}
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();
    }
}
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();
        
    }
}
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();
    }
}
image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 概要本章,会对线程等待/唤醒方法进行介绍。涉及到的内容包括: wait(), notify(), notifyAl...
    博格体阅读 325评论 0 0
  • 在典型的Java面试中, 面试官会从线程的基本概念问起, 如:为什么你需要使用线程, 如何创建线程,用什么方式创建...
    汤_tom阅读 376评论 0 0
  • 理解程序、进程、线程的概念程序可以理解为静态的代码进程可以理解为执行中的程序 线程可以理解为进程的进一步细分,程序...
    __豆约翰__阅读 649评论 0 4
  • 一、 填空题 1.处于运行状态的线程在某些情况下,如执行了sleep(睡眠)方法,或等待I/O设备等资源,将...
    蛋炒饭_By阅读 4,351评论 0 1
  • 1.解决信号量丢失和假唤醒 public class MyWaitNotify3{ MonitorObject m...
    Q罗阅读 917评论 0 1