search
HomeJavajavaTutorialJava thread (anonymous inner class)
Java thread (anonymous inner class)Dec 15, 2016 pm 01:07 PM
anonymous inner class

1 Thread object

Java code

Thread t = new Thread(  
                new Thread(){  
                    @Override  
                    public void run() {  
                      
                        while(true){  
                            try {  
                                Thread.sleep(1000);  
                            } catch (InterruptedException e) {  
                                e.printStackTrace();  
                            }  
                            System.out.println("1: "+Thread.currentThread().getName());  
                            System.out.println("2: "+this.getName());  
                        }                         
                          
                    }  
                }  
        );  
        t.start();

2 Runnable interface

Java code

Thread t2 = new Thread(  
                new Runnable(){  
                    @Override  
                    public void run() {  
                          
                        while(true){  
                            try {  
                                Thread.sleep(1000);  
                            } catch (InterruptedException e) {  
                                e.printStackTrace();  
                            }  
                            System.out.println("3: "+Thread.currentThread().getName());                           
                        }                         
                    }  
                }  
        );  
        t2.start();

Which part of the code will be executed below!

Java code

//只要重写了run方法,你从构造函数传递进去的线程对象就不会在执行        
        new Thread(new Runnable(){  
              
            @Override  
            public void run() {  
                  
                while(true){  
                    try {  
                        Thread.sleep(1000);  
                    } catch (InterruptedException e) {  
                        e.printStackTrace();  
                    }  
                    System.out.println("runnable: "+Thread.currentThread().getName());                            
                }                         
            }  
        }  
        ){  
              
            @Override  
            public void run() {  
                  
                while(true){  
                    try {  
                        Thread.sleep(1000);  
                    } catch (InterruptedException e) {  
                        e.printStackTrace();  
                    }  
                    System.out.println("thread: "+Thread.currentThread().getName());                              
                }  
                  
            }  
        }.start();

The output results are as follows:

Log code

3: Thread-2  
1: Thread-1  
2: Thread-0  
thread: Thread-3

The following code comes from: JAVA Programming Thoughts 4th Edition, explaining the difference between adding threads or not!
Counter1.java shows the performance of not adding threads !

Java code

import java.awt.*;  
import java.awt.event.*;  
import java.applet.*;  
  
public class Counter1 extends Applet {    
      
    private static final long serialVersionUID = 1L;  
    private int count = 0;  
    private Button onOff = new Button("Toggle"), start = new Button("Start");  
    private TextField t = new TextField(10);  
    private boolean runFlag = true;  
  
    public void init() {  
        add(t);  
        start.addActionListener(new StartL());  
        add(start);  
        onOff.addActionListener(new OnOffL());  
        add(onOff);  
    }  
  
    @SuppressWarnings("static-access")  
    public void go() {  
        while (true) {  
            try {  
                Thread.currentThread().sleep(100);  
            } catch (InterruptedException e) {  
            }  
            if (runFlag)  
                t.setText(Integer.toString(count++));  
  
        }  
    }  
  
    class StartL implements ActionListener {  
        public void actionPerformed(ActionEvent e) {  
            go();  
        }  
    }  
  
    class OnOffL implements ActionListener {  
        public void actionPerformed(ActionEvent e) {  
            runFlag = !runFlag;  
        }  
    }  
  
    public static void main(String[] args) {  
        Counter1 applet = new Counter1();  
        Frame aFrame = new Frame("Counter1");  
        aFrame.addWindowListener(new WindowAdapter() {  
            public void windowClosing(WindowEvent e) {  
                System.exit(0);  
            }  
        });  
        aFrame.add(applet, BorderLayout.CENTER);  
        aFrame.setSize(300, 200);  
        applet.init();  
        applet.start();  
        aFrame.setVisible(true);  
    }  
}

Counter2i.java added threads and the result was quite different. An internal class was added, which inherited Thread

Java code

import java.awt.*;  
import java.awt.event.*;  
import java.applet.*;  
  
public class Counter2i extends Applet {  
      
    private static final long serialVersionUID = 1L;  
  
    private class SeparateSubTask extends Thread {  
        int count = 0;  
        boolean runFlag = true;  
  
        SeparateSubTask() {  
            start();  
        }  
  
        public void run() {  
            while (true) {  
                try {  
                    sleep(100);  
                } catch (InterruptedException e) {  
                }  
                if (runFlag)  
                    t.setText(Integer.toString(count++));  
            }  
        }  
    }  
  
    private SeparateSubTask sp = null;  
    private TextField t = new TextField(10);  
    private Button onOff = new Button("Toggle"), start = new Button("Start");  
  
    public void init() {  
  
        add(t);  
        start.addActionListener(new StartL());  
        add(start);  
        onOff.addActionListener(new OnOffL());  
        add(onOff);  
    }  
  
    class StartL implements ActionListener {  
        public void actionPerformed(ActionEvent e) {  
            if (sp == null)  
                sp = new SeparateSubTask();  
        }  
    }  
  
    class OnOffL implements ActionListener {  
        public void actionPerformed(ActionEvent e) {  
            if (sp != null)  
                sp.runFlag = !sp.runFlag; // invertFlag();  
        }  
    }  
  
    public static void main(String[] args) {  
        Counter2i applet = new Counter2i();  
        Frame aFrame = new Frame("Counter2i");  
        aFrame.addWindowListener(new WindowAdapter() {  
            public void windowClosing(WindowEvent e) {  
                System.exit(0);  
            }  
        });  
        aFrame.add(applet, BorderLayout.CENTER);  
        aFrame.setSize(300, 200);  
        applet.init();  
        applet.start();  
        aFrame.setVisible(true);  
    }  
}

Counter3.java which implemented the Runnable interface

Java code

import java.awt.*;  
import java.awt.event.*;  
import java.applet.*;  
  
public class Counter3 extends Applet implements Runnable {  
      
    private static final long serialVersionUID = 1L;  
    private int count = 0;  
    private boolean runFlag = true;  
    private Thread selfThread = null;  
    private Button onOff = new Button("Toggle"), start = new Button("Start");  
    private TextField t = new TextField(10);  
  
    public void init() {  
        add(t);  
        start.addActionListener(new StartL());  
        add(start);  
        onOff.addActionListener(new OnOffL());  
        add(onOff);  
    }  
  
    @SuppressWarnings("static-access")  
    public void run() {  
        while (true) {  
            try {  
                selfThread.sleep(100);  
            } catch (InterruptedException e) {  
            }  
            if (runFlag)  
                t.setText(Integer.toString(count++));  
        }  
    }  
  
    class StartL implements ActionListener {  
        public void actionPerformed(ActionEvent e) {  
            if (selfThread == null) {  
                selfThread = new Thread(Counter3.this);  
                selfThread.start();  
            }  
        }  
    }  
  
    class OnOffL implements ActionListener {  
        public void actionPerformed(ActionEvent e) {  
            runFlag = !runFlag;  
        }  
    }  
  
    public static void main(String[] args) {  
        Counter3 applet = new Counter3();  
        Frame aFrame = new Frame("Counter3");  
        aFrame.addWindowListener(new WindowAdapter() {  
            public void windowClosing(WindowEvent e) {  
                System.exit(0);  
            }  
        });  
        aFrame.add(applet, BorderLayout.CENTER);  
        aFrame.setSize(300, 200);  
        applet.init();  
        applet.start();  
        aFrame.setVisible(true);  
    }  
}



For more articles related to Java threads (anonymous internal classes), please pay attention to the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Java 匿名内部类如何解决内存泄漏问题?Java 匿名内部类如何解决内存泄漏问题?May 01, 2024 pm 10:30 PM

匿名内部类可导致内存泄漏,问题在于它们持有外部类的引用,从而阻止外部类被垃圾回收。解决方法包括:1.使用弱引用,当外部类不再被强引用持有时,垃圾回收器会立即回收弱引用对象;2.使用软引用,垃圾回收器会在进行垃圾回收时需要内存时才回收软引用对象。在实战中,例如Android应用中,可以通过使用弱引用来解决因匿名内部类引起的内存泄漏问题,从而在不需要监听器时回收匿名内部类。

Java 匿名内部类的设计模式有哪些?Java 匿名内部类的设计模式有哪些?May 02, 2024 pm 04:42 PM

匿名内部类是Java中没有显式名称、通过new表达式创建的特殊内部类,主要用于实现特定接口或扩展抽象类,并在创建后立即使用。常见的匿名内部类设计模式包括:适配器模式:将一个接口转换为另一个接口。策略模式:定义和替换算法。观察者模式:注册观察者并处理事件。它在实际应用中非常有用,例如按字符串长度排序TreeSet、创建匿名线程等。

Java 匿名内部类有哪些优势?Java 匿名内部类有哪些优势?Apr 30, 2024 am 11:39 AM

匿名内部类在Java中作为方便创建子类、简化代码和处理事件(例如按钮单击)的特殊内部类。实战案例包括:事件处理:使用匿名内部类为按钮添加单击事件监听器。数据转换:使用Collections.sort方法和匿名内部类作为比较器对集合进行排序。

Java 匿名内部类的生命周期是怎样的?Java 匿名内部类的生命周期是怎样的?May 01, 2024 pm 04:06 PM

匿名内部类的生命周期由其作用域决定:方法局部内部类:仅在创建它的方法范围内有效。构造器内部类:与外部类实例绑定,当外部类实例释放时释放。静态内部类:与外部类同时加载卸载。

Java 匿名内部类有哪些常见错误?Java 匿名内部类有哪些常见错误?May 02, 2024 am 09:03 AM

匿名内部类使用错误:在非线程安全环境中使用捕获未声明的异常访问超出范围的变量

Java 匿名内部类如何优化性能?Java 匿名内部类如何优化性能?May 02, 2024 am 08:48 AM

匿名内部类的性能问题在于每次使用都会重新创建,可通过以下策略优化:1.将匿名内部类存储在局部变量中;2.使用非静态内部类;3.使用lambda表达式。实战测试表明lambda表达式优化效果最佳。

Java 匿名内部类的替代方案是什么?Java 匿名内部类的替代方案是什么?Apr 30, 2024 pm 01:15 PM

Lambda表达式作为匿名内部类的替代方案,提供了更简洁的方式来定义函数式接口的实现:使用简短语法(parameters)->expression定义匿名函数。适用于需要实现函数式接口(只有一个抽象方法)的场合。能够简化列表排序和线程定义等任务。

Java 匿名内部类在哪些场景下不适合使用?Java 匿名内部类在哪些场景下不适合使用?May 03, 2024 pm 05:42 PM

匿名内部类不适合使用的情况有:需要访问私有成员需要多个实例需要继承需要访问泛型类型

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software