Want to become a Vibe Coder? Join Vibe Coding Training here
x
C# Corner
Tech
News
Videos
Forums
Jobs
Books
Events
More
Interviews
Live
Learn
Training
Career
Members
Blogs
Challenges
Certification
Contribute
Article
Blog
Video
Ebook
Interview Question
Collapse
Feed
Dashboard
Wallet
Learn
Achievements
Network
Refer
Rewards
SharpGPT
Premium
Contribute
Article
Blog
Video
Ebook
Interview Question
Register
Login
Another Thread Synchronization in C#
WhatsApp
Rajan Singh
Dec 29
2015
1
k
0
0
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
using
System.Threading.Tasks;
using
System.Threading;
namespace
AnotherThreadSynchronization
{
class
Program
{
static
object
baton =
new
object
();
static
Random rmd =
new
Random();
static
void
Main(
string
[] args)
{
for
(
int
i = 0; i < 6; i++)
{
new
Thread(AnotherThread)
.Start();
}
}
static
void
AnotherThread()
{
Console.WriteLine(Thread.CurrentThread.ManagedThreadId +
"- First cell"
);
lock
(baton)
{
Console.WriteLine(Thread.CurrentThread.ManagedThreadId +
"- Second cell"
);
Thread.Sleep(rmd.Next(2000));
Console.WriteLine(Thread.CurrentThread.ManagedThreadId +
"- Third cell"
);
}
Console.WriteLine(Thread.CurrentThread.ManagedThreadId +
"- Forth cell"
);
}
}
}
Output:
-
3- First cell
5- First cell
7- First cell
8- First cell
6- First cell
4- First cell
3- Second cell
3- Third cell
3- Forth cell
5- Second cell
5- Third cell
5- Forth cell
7- Second cell
7- Third cell
7- Forth cell
8- Second cell
8- Third cell
8- Forth cell
AnotherThreadSynchronization
C#
Up Next
Another Thread Synchronization in C#