0% found this document useful (0 votes)
13 views3 pages

CST 205 Ways To Create Threads in Java

Ways to create threads in Java. Codes and explanation

Uploaded by

Thanos
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views3 pages

CST 205 Ways To Create Threads in Java

Ways to create threads in Java. Codes and explanation

Uploaded by

Thanos
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

​In Java, there are two primary ways to create threads:

*1. Extending the Thread Class*

```
public class MyThread extends Thread {
@Override
public void run() {
// Thread code here
}
}

// Usage
MyThread thread = new MyThread();
thread.start();
```

*2. Implementing the Runnable Interface*

```
public class MyRunnable implements Runnable {
@Override
public void run() {
// Thread code here
}
}

// Usage
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
```

*Other Methods:*

*3. Using Anonymous Classes*

```
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
// Thread code here
}
});
thread.start();
```

*4. Using Lambda Expressions (Java 8 and later)*

```
Thread thread = new Thread(() -> {
// Thread code here
});
thread.start();
```

*5. Using Executor Framework (Java 5 and later)*

```
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.execute(new Runnable() {
@Override
public void run() {
// Thread code here
}
});
```

*6. Using Callable and Future (Java 5 and later)*

```
ExecutorService executor = Executors.newSingleThreadExecutor();
Callable<String> task = new Callable<String>() {
@Override
public String call() {
// Thread code here
return "Result";
}
};
Future<String> future = executor.submit(task);
```

*Comparison:*

| Method | Advantages | Disadvantages |


| --- | --- | --- |
| Extending Thread | Simple, easy to understand | Limited flexibility, can't extend other classes |
| Implementing Runnable | Flexible, can extend other classes | More verbose |
| Anonymous Classes | Convenient for small tasks | Limited readability |
| Lambda Expressions | Concise, easy to read | Limited to single-method interfaces |
| Executor Framework | Efficient, scalable | More complex setup |
| Callable and Future | Allows return values, exceptions | More complex setup |

Choose the method that best fits your use case, considering factors like readability, maintainability, and
performance.

Would you like more information on threading or concurrency in Java?

You might also like