a simple example of a multithreaded Delphi program. In this example, we'll create a Delphi application with two threads,
each printing messages to the console.
program MultithreadedApp; {$APPTYPE CONSOLE} uses SysUtils, Classes, Windows; type TMyThread = class(TThread) protected procedure Execute; override; end; procedure TMyThread.Execute; begin // Print messages from each thread while not Terminated do begin Writeln('Thread ID: ', GetCurrentThreadId, ' is running.'); Sleep(1000); // Sleep for 1 second end; end; var Thread1, Thread2: TMyThread; begin try // Create two threads Thread1 := TMyThread.Create(False); Thread2 := TMyThread.Create(False); // Wait for threads to finish Thread1.WaitFor; Thread2.WaitFor; except on E: Exception do Writeln('Exception: ', E.ClassName, ': ', E.Message); end; end.
In this code:
TMyThread is a custom thread class inherited from TThread. The Execute method is overridden to define the code that runs in the thread. Each thread prints its ID to the console every second using GetCurrentThreadId and Writeln. We create two instances of TMyThread, Thread1 and Thread2, passing False to the constructor to indicate that the threads should start running immediately. Finally, we call WaitFor on both threads to wait for them to finish executing.