对于下面的程序:
public class MyThread extends Thread{
private Object obj;
......
}
请问,这个MyThread里面的成员变量,是不是线程安全的?
因为,MyThread继承了Thread,其使用方式为:new MyThread().start();
所以,这就意味着,每次都是new了新对象,那么,他里面的各个成员变量就是这个对象自己拥有的,所以,是安全的。
我这样理解有问题吗?
ringa_lee2017-04-18 10:51:12
The overview of thread safety means that when multiple threads access the same object, if there is no need to consider the scheduling and alternate running of these threads in the runtime environment, there is no need for additional synchronization or any other coordination on the caller. Operations and actions calling this object can obtain correct results.
Judging the safety of multi-threading can be analyzed from the following three points:
1.明确哪些代码是多线程运行的代码,
2.明确共享数据,
3.明确多线程运行代码中哪些语句是操作共享数据.
If multiple threads operate a shared data, thread safety issues must be considered.
黄舟2017-04-18 10:51:12
The situation you mentioned is definitely thread-safe, because it is only used by your own thread.
阿神2017-04-18 10:51:12
Your understanding is correct, new MyThread().start()
Every time a new Thread object is used to start the thread, there is no sharing behavior, so it is thread-safe, the most voted answer
MyThread mt = new MyThread(); // 这里只 new 了一个对象,然后多线程操作,会存在线程安全问题
new Thread(mt).start();
new Thread(mt).start();
new Thread(mt).start();
// MyRunable mr = new MyRunable();
// new Thread(mr).start();
// new Thread(mr).start();
// new Thread(mr).start();
巴扎黑2017-04-18 10:51:12
A simple example
If you have a candy that others want to eat, then it is unsafe, so you find that you need a box and a lock to lock it up