threading using extend Thread - java

I can get my method threadR to run by a runnable thread, however i cant seem to get threadL to run as a thread and print out to the console
System.out.println("Greetings from Fred! threadL"); from my run thread
What am i doing wrong?
package threads;
import java.util.ArrayList;
import java.util.List;
public class Threads extends Thread implements Runnable {
private final List<Thread> threadList = new ArrayList<>();
private String e,l;
private Thread greetings;
public static void main(String[] args) {
String[] elements = {"Tim","Fred"};
Threads t = new Threads();
for (String e: elements) {
t.threadL(e);
t.threadR(e);
}
for(int index = 0;index<t.threadList.size();index++){
System.out.print(t.threadList.get(index).getName()+ " ID "+ t.threadList.get(index).getId()+"\n");
}
}
public List<Thread> threadL(String l) {
Thread greetings1 = new Thread(l);
greetings1.start();
threadList.add(greetings1);
//System.out.print(greetings.getName()+"\n");
//System.out.print(greetings.getId()+"\n");
return(threadList);
}
public List<Thread> threadR(String f) {
greetings = new Thread(f);
Thread greetingsFromFred = new Thread(greetings) {
#Override
public void run() {
System.out.println("Greetings from Fred! threadR");
}
}; greetingsFromFred.start();
threadList.add(greetings);
//System.out.print(greetings.getName()+"\n");
//System.out.print(greetings.getId()+"\n");
return(threadList);
}
public void run() {
System.out.println("Greetings from Fred! threadL"); //this is what wont run
}

When you pass a String as the only argument to new Thread(String); you are actually setting the Thread name. You probably meant to pass a Runnable to the Thread as such
Thread greetings1 = new Thread(this);
Thread Constructors

Related

Java Runnable without static reference

I am trying to learn multi-threading using the runnable interface but I am having some trouble figuring out how to pass information. Basically, in the example below, I want to remove the static reference from the Hashmap but if I do that, the program breaks. How do I pass the hashmap to the runnable interface class without using the static keyword?
public class ThreadDemo {
static HashMap <String, Integer>map = new HashMap<>();
public String Hi() {
return "hi";
}
public String Hello() {
return "Hello";
}
public void addToMap(String item) {
if (map.containsKey(item)) {
map.put(item, map.get(item) + 1);
} else {
map.put(item, 1);
}
}
public static void main(String[] args) throws InterruptedException {
ArrayList<Thread> all = new ArrayList<>();
for (int i = 0; i < 50; ++i) {
threader threader = new threader();
all.add(new Thread(threader));
}
for (Thread thread : all) {
thread.start();
}
for (Thread thread : all) {
thread.join();
}
ThreadDemo td = new ThreadDemo();
System.out.println(td.map);
}
}
And a class that implements Runnable
public class threader implements Runnable {
ThreadDemo td = new ThreadDemo();
#Override
public void run() {
synchronized(td.map) {
td.addToMap(td.Hi());
td.addToMap(td.Hello());
}
}
}
A class instance is all about information.
public class threader implements Runnable {
final private ThreadDemo td;
public threader(ThreadDemo td) {
this.td = td;
}
#Override
public void run() {
..
}
}
then to use (details omitted, just the idea):
ThreadDemo theTd = new ThreadDemo();
for (...) {
threader threader = new threader(theTd);
all.add(new Thread(threader));
}
....
Of course, all threads are using the same ThreadDemo, with the same map, so you'll need to ensure access is interlocked in some way, e.g., by using synchronized. The ThreadDemo.addToMap method should be synchronized in this example, rather than the caller of addToMap. This puts the responsibility for the "care of the map" into the place that actually owns the map, and is consequently a better design.
I chose to share the ThreadDemo rather than just the map inside the ThreadDemo, since it looks to me that the intent of ThreadDemo is just to be a wrapper around the map.

Passing command-line arguments to mutliple java threads

I'm trying to create multiple threads in a java program and have them perform arithmetic operations on integers passed as command-line arguments. Obviously neither of the thread classes I'm trying to pass to are in the main method so how can I still access a variable like args[0] from these classes?
public class Mythread {
public static void main(String[] args) {
Runnable r = new multiplication();
Thread t = new Thread(r);
Runnable r2 = new summation();
Thread t2 = new Thread(r2);
t.start();
t2.start();
}
}
class summation implements Runnable{
public void run(){
System.out.print(args[0]);
}
}
class multiplication implements Runnable{
public void run(){
System.out.print(args[1]);
}
}
You should pass in the necessary information in the constructor
class Summation implements Runnable {
private final String info;
public Summation(String info) {
this.info = info;
}
#Override
public void run(){
System.out.print(info);
}
}
Then you can pass in the args values to your threads in main so that you have them in your runnables / threads
public class Mythread {
public static void main(String[] args) {
Runnable r = new multiplication(args[1]);
Thread t = new Thread(r);
Runnable r2 = new summation(args[0]);
Thread t2 = new Thread(r2);
t.start();
t2.start();
}
}

Not able to implement threads as required in Java

I am having trouble implementing the below scenario as I am new to multithreading. Can anyone help me with this?
The requirement is as below:
One thread created prime numbers from 1 to infinity. Another thread that writes those numbers to the console. Write code that runs these two threads.
This is what I tried:
class func1 implements Runnable{
public void run(){
int x=1, counter=0;
for (int i=0; i<=infinity; i++){
if (isPrime(i)){
p[counter] = i;
counter++;
}
}
}
}
class func2 implements Runnable{
public void run(){
int x=1, counter=0;
int[] p=0;
for (int i=0; i<=infinity; i++){
System.out.println(“Prime number:”+p[i]);
}
}
}
public class test{
static volatile int[] arr;
public static void main(String[] args){
func1 obj1 = new func1(arr);
func2 obj2 = new func2(arr);
thread t1, t2;
t1 = new thread(obj1);
t2 = new thread(obj2);
t1.start();
t2.start();
}
Here is a simple example of producer consumer pattern. Producer creates some integer values, populates them in a blocking queue and consumer pulls them from the queue.
Producer:
import java.util.concurrent.BlockingQueue;
public class Producer implements Runnable{
BlockingQueue<Integer> queue;
public Producer(BlockingQueue<Integer> queue){
this.queue = queue;
}
#Override
public void run() {
for(int i=0;i<10;i++){
queue.offer(i);
}
}
}
Consumer:
import java.util.concurrent.BlockingQueue;
public class Consumer implements Runnable {
BlockingQueue<Integer> queue;
public Consumer(BlockingQueue<Integer> queue) {
this.queue = queue;
}
#Override
public void run() {
while (true) {
if (queue.peek() != null) {
Integer number = queue.poll();
System.out.println("Integer is >>> " + number);
}
}
}
}
Test class:
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class Main {
public static void main(String args[]) {
BlockingQueue queue = new ArrayBlockingQueue(10);
Producer producer = new Producer(queue);
Consumer consumer = new Consumer(queue);
Thread producerThread = new Thread(producer);
Thread consumerThread = new Thread(consumer);
producerThread.start();
consumerThread.start();
}
}
You can produce/consume primes. The logic inside run() method of Producer/Consumer will change. This can also be implemented using wait/notify.

How to get the output stream from a thread

I currently have several runnable classes, each printing a string upon completion using System.out.println().
In the main() I execute them using a ExecutorService ,executor.execute() for each of them.
I am wondering after executing those threads, how to get the output stream from them for future use ?
Pretty much like using .getInputStream for processes but there's no such method in the Thread class. Thanks!
There's a class which implements runnable interface like this:
public class A implements Runnable {
public void run() {
System.out.println(5); //this thread always print out number 5
}
}
and in the main function I need to get the printed number and store it
public static void main(String[] args) {
ExecutorService ThreadPool = Executors.newFixedThreadPool(1);
ThreadPool.execute(new A()); //This statement will cause the thread object A
//to print out number 5 on the screen
ThreadPool.shutdown();
......
}
Now I need to get the printed number 5 and store it into, say an integer variable.
I think below code will satisfy your requirement.
class MyCallable implements Callable<InputStream>
{
#Override
public InputStream call() throws Exception {
//InputStream inputStreamObject = create object for InputStream
return inputStreamObject;
}
}
class Main
{
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(5);
List<Future<InputStream>> list = new ArrayList<Future<InputStream>>();
for (int i = 0; i < 25; i++) {
Callable<InputStream> worker = new MyCallable();
Future<InputStream> submit = executor.submit(worker);
list.add(submit);
}
InputStream inputStreamObject = null;
for (Future<InputStream> future : list) {
try {
inputStreamObject = future.get();
//use inputStreamObject as your needs
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
executor.shutdown();
}
}
Runnable and Callable in thread:
runnable interface has a method public abstract void run(); void - which means after completing run method, it will not return anything. Callable<V> interface has a method V call() throws Exception; which means after completing call method, it will return Object V that is parametrized as
public class Run_Vs_Call {
public static void main(String...args){
CallableTask call = new CallableTask();
RunnableTask run = new RunnableTask();
try{
FutureTask<String> callTask = new FutureTask<String>(call);
Thread runTask = new Thread(run);
callTask.run();
runTask.start();
System.out.println(callTask.get());
}catch(Exception e){
e.printStackTrace();
}
}
public static class CallableTask implements Callable<String>{
public String call( ){
String stringObject = "Inside call method..!! I am returning this string";
System.out.println(stringObject);
return stringObject;
}
}
public static class RunnableTask implements Runnable{
public void run(){
String stringObject = "Inside Run Method, I can not return any thing";
System.out.println(stringObject);
}
}
}
you can use new static class:
public class Global{
//example
public static ..
public static ..
}

Java multi-threads programming

I am a beginner of Java programming learner. I can't know how to correct the following Java program. Kindly help to let me know how to correct it. Thanks a lot.
public class TMA1Q2 {
public static void main(String[] args) {
System.out.println("Usage: java TMA1Q2 {number of Threads}");
// Create tasks
Runnable taskA = new PrintTwoConcurThreads("Thread A ");
Runnable taskB = new PrintTwoConcurThreads(" Thread B ");
// Create threads
Thread thread1 = new Thread(taskA);
Thread thread2 = new Thread(taskB);
// Start threads
thread1.start();
thread2.start();
}
}
// The task that implements Runnable
class PrintTwoConcurThreads implements Runnable {
private final String TwoConcurThreads;
private String[] args;
public PrintTwoConcurThreads(String numThreads) {
TwoConcurThreads = numThreads;
}
// Override the run() method
#Override
public void run() {
// Print the value input argument times
int numThreads = Integer.parseInt(args[0]);
Thread[] myThread;
myThread = new Thread[numThreads];
for (int i = 0; i < numThreads; i++) {
System.out.println(TwoConcurThreads + i);
}
}
}
private String[] args;
This args field is never initialized, so it will be having a default value of null.
When you try to access it in following line you get a NullPointerException
int numThreads = Integer.parseInt(args[0]);
It is not clear what you're trying to do. Atleast this would help you to see what's going wrong.
Also I have no Idea why following lines are used, You create Thread[] but never you used it.
Thread[] myThread;
myThread = new Thread[numThreads];

Categories

Resources