英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论