JAVA Runnable类和启动线程之间有什么区别?

huangapple go评论47阅读模式
英文:

What is the difference between JAVA Runnable class to start thread?

问题

The difference between mode 1 and mode 2 start thread?
方法1:我使用相同的Runnable对象启动多个线程
方法2:我使用不同的Runnable对象启动多个线程

package com.hbase.a;

public class MyThreadB implements Runnable {
    private  int tik = 100;

    public void run() {
       //do ...
    }

 
    public static void main(String[] args) {
        // 方法1
        MyThreadB myThreadB = new MyThreadB();
        new Thread(myThreadB).start();
        new Thread(myThreadB).start();
        new Thread(myThreadB).start();
        new Thread(myThreadB).start();
       
        // 方法2
        new Thread(new MyThreadB()).start();
        new Thread(new MyThreadB()).start();
        new Thread(new MyThreadB()).start();
        new Thread(new MyThreadB()).start();

    }
}
英文:

The difference between mode 1 and mode 2 start thread?

Method 1: I use the same Runnable object to start multiple threads

Method 2: I use different Runnable objects to start multiple threads

package com.hbase.a;

public class MyThreadB implements Runnable {
    private  int tik = 100;

    public void run() {
       //do ...
    }

 
    public static void main(String[] args) {
        // method-1 
        MyThreadB myThreadB = new MyThreadB();
        new Thread(myThreadB).start();
        new Thread(myThreadB).start();
        new Thread(myThreadB).start();
        new Thread(myThreadB).start();
       
        // method -2 
        new Thread(new MyThreadB()).start();
        new Thread(new MyThreadB()).start();
        new Thread(new MyThreadB()).start();
        new Thread(new MyThreadB()).start();

    }
}

答案1

得分: 4

使用第一种方法,存在一个共享于所有线程之间的MyThreadB对象。这意味着只有一个tik变量,可能被所有4个线程写入和读取。这个共享变量可以用来在一个线程之间传递信息,但这很容易导致意外行为(错误)。

使用第二种方法,每个线程都拥有自己的对象。有4个独立的MyThreadB对象,每个对象都有自己的tik变量。当一个线程更改其对象中的tik变量时,其他线程无法看到这个变化。

英文:

With the first method, there is one single MyThreadB object that is shared between all threads. That means that there is only one tik variable, which might be written and read by all 4 threads. This shared variable could be used to pass information from one thread to another, but this easily leads to unintended behavior (bugs).

With the second method, each thread gets an object of its own. There are 4 independent MyThreadB objects, each with a tik variable of its own. When one thread changes the tik variable in its object, it cannot be seen by the other threads.

huangapple
  • 本文由 发表于 2020年8月1日 00:36:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/63195803.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定