TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
C# Corner
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Another Thread Synchronization in C#
Rajan Singh
Dec 29
2015
Code
998
0
0
facebook
twitter
linkedIn
Reddit
WhatsApp
Email
Bookmark
expand
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#