Question: I'm making a desktop app in Java Swing using the Netbeans platform. I want to convert a 16 bit gray scale image to an RGB image. How can I do that?

Answer: 
Generally this (calling TerminateThread) is a bad thing to do because a thread may allocate some resources (i.e., file descriptors) which will be unavailable until the whole process terminate. Even more, the CloseHandle does not stop the thread.

If you have some lengthy operation inside your thread, then at least use the

```
while(!ShouldExit)
{
     DoOneMoreIteration();
}

```

cycle. This way you can terminate the thread by setting ShouldExit to 1 (or 'true', if it is C++ and bool variable) and the call WaitForSingleObject on this thread's handle to ensure it has finished.

For eran's comment: The ShouldExit must be declared as 'volatile'.

If you're waiting for some input (a console I suppose), then you might use the non-blocking ("overlapped") I/O with standard input.

E.g., see this question: [Checking Win32 file streams for available input](https://stackoverflow.com/questions/8347642/checking-win32-file-streams-for-available-input)

It would be something like

```
HANDLE h = GetStdHandle(STD_INPUT_HANDLE);

while(!ShouldExit) {
   if(WaitForSingleObject(h, FALSE, SomeTimeoutValue) == WAIT_OBJECT_0)
   {
      ... use std::cin - it has some input and won't block
   }
}

```

To make things better (avoid CPU overburn) use WaitForMultipleObjects and break outside the loop on some external event.

```
/// Global var
HANDLE SomeGlobalEvent;

/// ThreadProc():
HANDLE h[2];
h[0] = GetStdHandle(STD_INPUT_HANDLE);
h[1] = SomeGlobalEvent;

while(true) {
   DWORD which = WaitForMultipleObjects(2, h, FALSE, SomeTimeoutValue);
   if(which == WAIT_OBJECT_0)
   {
      ... use std::cin - it has some input and won't block
   } else
   if(which == WAIT_OBJECT_1)
   {
      // got the termination event
      break;
   }
}

/// "Main" thread:

SomeGlobalEvent = CreateEvent(NULL, false, false, NULL);

HANDLE hThread = _beginthread(ThreadProc, 4096, NULL);

 ....
 /// send termination signal
 SetEvent(SomeGlobalEvent);

 /// Wait for thread completion
 WaitForSingleObject(hThread);

```
Best thing is to read the docs carefully. Win32 API is well documented.

from [MSDN on CreateThread in the Remarks section](http://msdn.microsoft.com/en-us/library/ms885186.aspx) it says

> 
> Thread execution begins at the function specified by the lpStartAddr
>  parameter. If this function returns, the DWORD return value is used to
>  terminate the thread in an implicit call to the ExitThread function.
>  Use the GetExitCodeThread function to get the thread's return value.
> 
> 
> 

Following on from that, you should let the thread entry function do its job and finish. I.e. exit the loop which would return the thread entry function.