java - 通过run方法和Start方法执行Thread

标签 java multithreading thread-safety

我正在尝试使用 thread.Run 以及 thread.start 将 Thread 执行到 Both 方法中

是这样的 主类

Thread thread = new GetTimeZones();
ByImletingInterface thread21 = new ByImletingInterface();
thread21.getMailStarttime(5);

ByImletingInterface thread2 = new ByImletingInterface();
thread2.getMailStarttime(10);

thread.start();
new Thread(thread21).start();
new Thread(thread2).start();

线程 1

public class ByImletingInterface implements Runnable {
    private int starttime;

    @Override
    public void run() {
        // TODO Auto-generated method stub
        try {
            Thread.sleep(starttime * 1000);
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println(e);
        }
        System.out.println("Checking Mail");
    }

}

和其他人

public class GetTimeZones extends Thread {

    @SuppressWarnings("static-access")
    @Override
    public void run() {
        // TODO Auto-generated method stub
        Locale locale;
        DateFormat timeforMatter;
        DateFormat dateforMatter;
        String timeoutput = null;
        String dateoutput = null;

        try {
            java.util.Date date;

            for (int i = 0; i < 20; i++) {
                date = new Date();
                locale = new Locale("en");

                timeforMatter = DateFormat.getTimeInstance(DateFormat.DEFAULT,
                        locale);
                dateforMatter = DateFormat.getDateInstance(DateFormat.DEFAULT,
                        locale);

                //System.out.println(timeforMatter);
                timeoutput = timeforMatter.format(date);
                dateoutput = dateforMatter.format(date);

                System.out.println(timeoutput);
                System.out.println(dateoutput);
                System.out.println();


                try {
                    Thread.sleep(2000);
                } catch (Exception e) {
                    // TODO: handle exception
                }
            }

        } catch (Exception e) {
            // TODO: handle exception
            System.out.println(e);
            e.printStackTrace();
        }

        super.run();
    }
}

如何描述我的概率这两个类都不是必需的,但我仍然提供它。

当我像以前一样在主类中使用 therad.start 时。它有意识地执行三个线程。

但是当我使用 theread.run 一个一个地执行时。意味着它的同步。为什么会这样?

最佳答案

当你调用 run() 方法时,你是在当前线程上运行它,所以它当然会一个接一个地运行,因为只有一个线程(每个 run () 方法将在前一个完成后执行)。

只有当您调用 start() 时,才会创建一个新线程,并在该新线程中执行 run() 方法。

关于java - 通过run方法和Start方法执行Thread,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30302580/

相关文章:

Java JScrollPane 未按预期工作

java - 动态创建类

java - 需要关于用于学术研究的 Java 开源项目的推荐

java - 当我通过 Swing 执行 get LDAPConnection 时,它挂起

multithreading - 既然 U32 已经实现了同步,为什么还要在 Rust 中使用 AtomicU32?

c++ - C++ 中的线程安全单例

java - 将 UMLS 用户名和密码添加到 Ctakes

java - Session.sendToTarget() 是线程安全的吗?

java - 从android中的线程中检索应用程序上下文

python - 将线程传递给线程对象