(多线程)在类内和类外:两种创建线程的方式执行过程有哪些不同?
请教各位前辈,用如下两种方式创建启动的线程,执行过程有哪些不同?谢谢各位
“方式一:使用ThreadA类创建3个线程”和“方式二:使用ThreadB类创建3个线程”
/// <summary>
/// 类ThreadA
/// </summary>
public class ThreadA
{
private Thread Th;
private int number;
public ThreadA(int n)
{
Th = new Thread(new ThreadStart(this.Run));
this.number = n;
}
public void Start()
{
if (Th != null)
{
Th.Start();
}
}
private void Run()
{
if (this.number > 0)
{
//线程执行方法代码,略……
}
}
}
/// <summary>
/// 类ThreadB
/// </summary>
public class ThreadB
{
private int number;
public ThreadB(int n)
{
this.number = n;
}
public void Run()
{
if (this.number > 0)
{
//线程执行方法代码,略……
}
}
}
class Program
{
static void Main(string[] args)
{
//方式一:使用ThreadA类创建3个线程
ThreadA ThA1 = new ThreadA(1);
ThA1.Start();
ThreadA ThA2 = new ThreadA(2);
ThA2.Start();
ThreadA ThA3 = new ThreadA(3);
ThA3.Start();
//方式二:使用ThreadB类创建3个线程
ThreadB ThB1 = new ThreadB(10);
Thread Th1 = new Thread(new ThreadStart(ThB1.Run));
Th1.Start();
ThreadB ThB2 = new ThreadB(11);
Thread Th2 = new Thread(new ThreadStart(ThB2.Run));
Th2.Start();
ThreadB ThB3 = new ThreadB(11);
Thread Th3 = new Thread(new ThreadStart(ThB3.Run));
Th3.Start();
}
}
[最优解释]
本质上没有什么不同,但是从设计上要看那一种符合你设计的需要。
就好比普通的代码,你把某些代码写入函数内,还是留给调用者自己写,一个道理。
[其他解释]
是一样的。
如果你想把线程操作封装起来就用A,想要调用private Run方法,就必须使用规定的方式(线程)。
如果你想让调用者自行决定是否使用线程,那么就用B。
具体得看你的业务和使用场景。
[其他解释]
类内和类外执行起来没什么不同,但就封装而言,如果外部不需要知道线程细节,还是封装在类内比较好,
[其他解释]
有人说执行起来不同,所以拿出来问大家。