100分在线等C# 多线程优先级和lock线程同步问题

来源:百度知道 编辑:UC知道 时间:2024/06/17 10:50:45
代码和运行结果在图片中,请放大查看!
问题1:子线程优先级为最高,为什么第一个显示的结果是主线程显示的1?
thread1.Priority = ThreadPriority.Highest;
我错在哪了?
问题2:我写的代码为什么是这种结果?
与我预期的结果截然不同。
我预期的结果是
A
子线程
B
子线程
C
子线程
D
子线程
1
主线程
2
主线程
3
主线程
4
主线程
我错在哪了求求各位大师,帮帮忙啊。
在这里我粘贴图中的代码
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Program program = new Program();
Thread.CurrentThread.Name = "主线程";
Thread thread1 = new Thread(new ThreadStart(program.fun1));
thread1.Priority = ThreadPriority.Highest;
thread1.Name = "子线程";
thread1.Start();

for (int i = 1; i < 5; i++)
{

owen27 正解,
补充一下:
操作系统在调度 各个线程 时,,是以 线程的 优先级 来决定
下一个时间片 是否是 用来 运行 它的,

你看的输出 结果来看,,我们可以这样来分析:

Main 方法所在的线程,一开始就获得运行,也就是占用了
你这个Console 应用的 第一时间片,
在这一时间片内它可以做很多工作,包括了,创建你的子线程,
并且在开始 for 循环 已经打印了 I 的时候, 时间片用尽,
操作系统再度(在处理完其它高优先级进程的事务后)
调度度你的 console 应用进程时, 发现了比 main 线程 优先级高的
"子线程"(如果你的子线程是 多个的话,可以明显体现出来, 高优先级线程 会被优先调用) 就把 执行权 分配给了 子线程 .

再进一步 子线程 执行到 for 循环的刚好打印了 69 后,时间片用尽,
操作系统再度进入 新的调度....

直到所有工作完成.

明白了吧.!!

-------------------------
不好意思,,我测试了一下,,不是我想的.

不过你预期的目标, 如果非要 多线程 实现的话,C#里
可以在 一个线程中 调用 join 来等待另一个线程 结束后再
继续执行.

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace ConsoleApplication1
{
class Program
{
static Thread t1, t2;
static void Main(string[] args)
{
Console.Writ