A question regarding an error when processing a java with multithreads? - multithreading

Please help me figure out what when wrong in this coding.
import java.lang.Thread;
class MyThread1 extends Thread
{ public void run()
{ for(int x=1;x<=15;x++)
{ if(x==10)
{ stop();
}
System.out.println(x);
}
}
}
class MyMain
{ public static void main(String args[])
{ MyThread1 first_thread=new MyThread1();
first_thread.start();
}
}
the error is
Note: MyClass.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.

The problem is that you should not call Thread.stop(). It is deprecated and dangerous.
Read Thread.stop() - deprecated to find out why stop() is deprecated. Or the javadoc.
If you want the thread to terminate itself, it can simply return from the run() method:
public void run() {
for (int x = 1; x <= 15; x++) {
if (x == 10) {
return;
}
}
}
or throw an unchecked exception:
public void run() {
for (int x = 1; x <= 15; x++) {
if (x == 10) {
throw new RuntimeException("It is 10am and your pants are on fire!");
}
}
}
Obviously, you should choose a more appropriate exception and message ...

Related

Why this code is giving IllegalMonitor Exception, when doing synchronization on instance variable

If I do synchronization on the lock, an Object, it works properly. However, if I do synchronization on number, an Integer, it throws an exception. Please help.
Below is my code:
package synchronization;
public class EvenOddThread implements Runnable {
int reminder;
Integer number = 1;
static Object lock = new Object();
public EvenOddThread( int reminder)
{
this.reminder = reminder;
}
public void run()
{
while(number < 10)
{
synchronized (number)
{
while(number %2 != reminder)
{
try
{
System.out.println(Thread.currentThread().getName()+" is waiting at "+number+" "+reminder);
number.wait();
}
catch(Exception e)
{
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+ " "+number );
number = number +1;
System.out.println(number);
//synchronized (lock) {
number.notifyAll();
//}
}
}
}
}

Implementing custom Executor

In the example below if I implement ExecutorImpl without using Thread, then taskCompletionService.submit is blocked, even though it returns Future.
Is it possible to not block submit, but not use Thread in ExecutorImpl?
class ExecutorServiceTest {
private static class ExecutorImpl implements Executor {
public void execute(Runnable r) {
final Thread t = new Thread(new Runnable() {
public void run() {
r.run();
}});
t.start();
//If used will block others.
//r.run();
}
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
final Executor executor = new ExecutorImpl();
final CompletionService<String> taskCompletionService = new ExecutorCompletionService<>(executor);
int submittedTasks = 3;
for(int i = 0; i < submittedTasks; i++) {
final int j = i;
//here it is blocked if ExecutorServiceIml doesn't utilize Thread
taskCompletionService.submit(new Callable<String>() {
public String call() throws Exception {
Thread.sleep((3 - j) * 1000);
return "callable:" + String.valueOf(j);
}
});
System.out.println("Task " + String.valueOf(i) + " has been submitted...");
}
for(int tasksHandled=0; tasksHandled < submittedTasks; tasksHandled++) {
try {
final Future<String> result = taskCompletionService.take();
String l = result.get();
System.out.println("Task has completed - result: " + l);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}
}

java.lang.NullPointerException while drawing in java.awt

I want to draw some balls and interact with them, but when I run my program I see my balls staying still and i get java.lang.NullPointerException error. Can u tell me what I'm doing wrong?
Main class:
public class Main extends JPanel {
// creating big ball
Big big = new Big(this);
// creating small balls
Small small_list = new Small(40);
// method for moving big ball
private void moveBig() throws InterruptedException{
big.move();
}
// same but small balls
private void moveSmall() throws InterruptedException{
// ERROR
small_list.move();
}
// paiting
#Override
public void paint(Graphics g){
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
big.paint(g2d);
big.paintLine(g2d);
small_list.paint(g2d);
}
public static void main(String[] args) throws InterruptedException {
// TODO code application logic here
JFrame window = new JFrame("test");
Main main = new Main();
window.add(main);
window.setSize(500,500);
window.setVisible(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
while(true){
main.moveBig();
// ERROR
main.moveSmall();
main.repaint();
Thread.sleep(15);
}
}
}
Big ball class:
public class Big {
// coordinates of first apperence
int x = 200;
int y = 200;
int upAnddown = 1;
int leftAndright = 1;
private static final int sizeOfbig = 30;
// list to draw a line after ball
private List<Point> listofpoints = new ArrayList<>();
private Main main;
public Big(Main main){
this.main=main;
}
void move() throws InterruptedException{
if (x+upAnddown < 5) {
upAnddown=1;
}
if (x+upAnddown > main.getWidth()-14) {
upAnddown=-1;
}
if (y+leftAndright < 5) {
leftAndright=1;
}
if (y+leftAndright > main.getHeight()-14) {
leftAndright=-1;
}
(...)
Small ball class:
public class Small {
int x = 20;
int y=20;
private static final int sizeOfSmall = 10;
int upAnddown = 1;
int leftAndright = 1;
private Main main;
public Small(Main main){
this.main=main;
}
public Small(int j){
ArrayList<Small> my_array = new ArrayList<Small>(j);
for (int i = 0; i < my_array.size(); i++) {
i=j;
my_array.add(new Small(i));
}
}
void move() throws InterruptedException{
//////////////////////////////////////
if (x+upAnddown < 0) {
upAnddown=1;
}
// ERROR
if (x+upAnddown > main.getWidth()-30) {
upAnddown=-1;
}
if (y+leftAndright < 0) {
leftAndright=1;
}
if (y+leftAndright > main.getHeight()-30) {
leftAndright=-1;
}
(...)
ERROR:
Exception in thread "main" java.lang.NullPointerException
at test2.Small.move(Small.java:56)
at test2.Main.moveSmall(Main.java:34)
at test2.Main.main(Main.java:67)
The while(true) will take all UI thread time. You need to put it in a thread to avoid that.
That's why balls stay still.
new Thread(new Runnable(){
public void run(){
while(true) {
main.moveBig();
main.moveSmall();
main.repaint();
Thread.sleep(15);
}
}
}).Start();
The NullPointerException may be related to this issue, I'm not sure. I don't see anything else that could raise it.

Trying to print a string character by character with delay between two character print

I've tried with code below. please guide me where i am wrong??? The desired output is like..
m(delay)e(delay)s(delay)s(delay)a(delay)g(delay)e.
import java.util.*;
import java.applet.*;
import java.awt.*;
/*<applet code="MessageWithDelay" width=400 height=200>
</applet>*/
public class MessageWithDelay extends Applet implements Runnable {
Thread t;
//char msg[] ={"m","e","s","s","a","g","e"};
String str = "message";
Graphics bufferg;
Image buffer;
int counter=0,x=str.length(),i=0;;
public void init() {
//initializa the thread
t = new Thread(this);
t.start();
Dimension d = getSize();
buffer = createImage(d.width,d.height);
}
public void run() {
try {
while(true)
{
//requesting repaint
repaint();
if(counter==x)
{
Thread.sleep(200);
counter=0;
i=0;
}
else
{
Thread.sleep(400);
}
}
}
catch(Exception e) {
}
}
public void update(Graphics g) {
paint(g);
}
public void paint(Graphics g) {
if(bufferg == null) {
Dimension d = getSize();
bufferg.setColor(Color.green);
g.setFont(new Font("Comic Sans MS",Font.BOLD,36));
bufferg.drawString(str.charAt(i)+"",20,20);
counter++;
i+=1;
//update screen
g.drawImage(buffer,0,0,this);
}
}
}
I am working on command prompt and its giving me bunch of different errors. I want to know why the errors occurring if anyone could explain me by trying it. Thanx in advance.
The problems I found include:
Use JApplet instead of Applet.
In the init method, create the buffer before starting the thread.
Update the buffer with the letters in the run method. The paint method just paints. No calculations.
Here's the working code. I formatted the code in Eclipse, an integrated development environment (IDE) for Java development.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.JApplet;
/*<applet code="MessageWithDelay" width=400 height=200>
</applet>*/
public class MessageWithDelay extends JApplet implements Runnable {
private static final long serialVersionUID = 1722008447683646619L;
Thread t;
String str = "message";
Image buffer;
#Override
public void init() {
Dimension d = getSize();
buffer = createImage(d.width, d.height);
// Initialize the thread
t = new Thread(this);
t.start();
}
#Override
public void run() {
int x = 40;
int y = 40;
for (int i = 0; i < str.length(); i++) {
Graphics g = buffer.getGraphics();
g.setFont(new Font("Comic Sans MS", Font.BOLD, 36));
g.setColor(Color.GREEN);
g.drawString("" + str.charAt(i), x, y);
g.dispose();
x += 40;
repaint();
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
}
}
}
#Override
public void update(Graphics g) {
paint(g);
}
#Override
public void paint(Graphics g) {
g.drawImage(buffer, 0, 0, this);
}
}

Implementing busy wait with a pair of flags

I am trying to implement a busy waiting mechanism, using 2 flags. I get a deadlock, but just can't understand why... it looks to me as if it should work...
sorry for the long code, That's the shortest I succeeded to make it.
package pckg1;
public class MainClass {
public static void main(String[] args) {
Buffer b = new Buffer();
Producer prod = new Producer(b);
Consumer cons = new Consumer(b);
cons.start();
prod.start();
}
}
class Producer extends Thread {
private Buffer buffer;
public Producer(Buffer buffer1) {
buffer = buffer1;
}
public void run() {
for (int i = 0; i < 60; i++) {
while (!buffer.canUpdate)
;
buffer.updateX();
buffer.canUpdate = false;
buffer.canUse = true;
}
}
}
class Consumer extends Thread {
private Buffer buffer;
public Consumer(Buffer buffer1) {
buffer = buffer1;
}
public void run() {
for (int i = 0; i < 60; i++) {
while (!buffer.canUse)
;
buffer.consumeX();
buffer.canUse = false;
buffer.canUpdate = true;
}
}
}
class Buffer {
private int x;
public boolean canUpdate;
public boolean canUse;
public Buffer() {
x = 0;
canUpdate = true;
}
public void updateX() {
x++;
System.out.println("updated to " + x);
}
public void consumeX() {
System.out.println("used " + x);
}
}
I recommend that all the logic concerning Buffer should go into that class.
Also, accessing (and modifying) the flags must be protected, if 2 or more have access to it. That's why I put synchronised to the 2 methods.
class Buffer {
private int x;
private boolean canUpdate;
private boolean canUse;
public Buffer() {
x = 0;
canUpdate = true;
}
public synchronised void updateX() {
x++;
System.out.println("updated to " + x);
canUpdate = false;
canUse = true;
}
public synchronised void consumeX() {
System.out.println("used " + x);
canUpdate = true;
canUse = false;
}
public synchronised boolean canUse() {
return canUse;
}
public synchronised boolean canUpdate() {
return canUpdate;
}
}
Also, remove the canUpdate and canUse writes from the Producer and Consumer classes, and replace the reads (in the conditons) with the methods.
Also, it would be useful to introduce some Thread.sleep(100) in the waiting loops.

Resources