Csharp/CSharp Tutorial/Thread/Thread Interrupt — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
Admin (обсуждение | вклад) м (1 версия) |
(нет различий)
|
Текущая версия на 12:20, 26 мая 2010
Interrupting a Thread
using System;
using System.Threading;
public class Interrupt {
public static Thread sleeper;
public static Thread worker;
public static void Main() {
sleeper = new Thread(new ThreadStart(SleepingThread));
worker = new Thread(new ThreadStart(AwakeTheThread));
sleeper.Start();
worker.Start();
}
public static void SleepingThread() {
for (int i = 1; i < 10; i++) {
Console.Write(i + " ");
Console.WriteLine("Going to sleep at: " + i);
Thread.Sleep(20);
}
}
public static void AwakeTheThread() {
for (int i = 11; i < 20; i++) {
Console.Write(i + " ");
if (sleeper.ThreadState == System.Threading.ThreadState.WaitSleepJoin) {
Console.WriteLine("Interrupting the sleeping thread");
sleeper.Interrupt();
}
}
}
}
Interrupting Threads
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
class Tester
{
static void Main()
{
Thread[] myThreads =
{
new Thread( new ThreadStart(Decrementer) ),
new Thread( new ThreadStart(Incrementer) ),
new Thread( new ThreadStart(Decrementer) ),
new Thread( new ThreadStart(Incrementer) )
};
int ctr = 1;
foreach (Thread myThread in myThreads)
{
myThread.IsBackground = true;
myThread.Start();
myThread.Name = "Thread" + ctr.ToString();
ctr++;
Console.WriteLine("Started thread {0}",myThread.Name);
Thread.Sleep(50);
}
myThreads[0].Interrupt();
myThreads[1].Abort();
foreach (Thread myThread in myThreads)
{
myThread.Join();
}
}
public static void Decrementer()
{
for (int i = 10; i >= 0; i--){
Console.WriteLine("Thread {0}. Decrementer: {1}",Thread.CurrentThread.Name, i);
Thread.Sleep(1);
}
Console.WriteLine("Thread {0} Exiting. ",Thread.CurrentThread.Name);
}
public static void Incrementer()
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine("Thread {0}. Incrementer: {1}",Thread.CurrentThread.Name, i);
Thread.Sleep(1);
}
Console.WriteLine("Thread {0} Exiting. ",Thread.CurrentThread.Name);
}
}
Sleep Interupt Threads
using System;
using System.Threading;
public class MainClass
{
public static int Main()
{
Thread X = new Thread(new ThreadStart(Sleep));
X.Start();
X.Interrupt();
X.Join();
return 0;
}
public static void Sleep()
{
try
{
Thread.Sleep(Timeout.Infinite);
}catch (ThreadInterruptedException e){
Console.WriteLine("Thread Interupted");
}catch(ThreadAbortException e){
Thread.ResetAbort();
}
}
}
Thread Interupted