Re: Threads interruption
here is whole program without my errors
import java.io.*;
public class Th extends Thread
{
private int which;
private static int[] howMany = {0, 0, 0, 0} ;
static boolean[] end = {true,true};
public Th(int which)
{
this.which= which;
}
public void run()
{
switch (which)
{
case 1: ThA(); break;
case 2: ThB(); break;
case 3: ThC(); break;
case 4: ThD(); break;
}
}
public void ThA()
{
while(true)
{
synchronized(howMany)
{
if ( (howMany[0]+howMany[1]) < (howMany[2]+howMany[3]) &&
(howMany[0] <= 2*howMany[1]))
{
System.out.print("A");
howMany[0]++;
}
}
try
{
sleep(100);
}
catch(InterruptedException e) {}
}
}
public void ThB()
{
while(true)
{
synchronized(howMany)
{
if ( (howMany[0]+howMany[1]) < (howMany[2]+howMany[3]) )
{
System.out.print("B");
howMany[1]++;
}
}
try
{
sleep(3200);
}
catch(InterruptedException e) {}
}
}
public void ThC()
{
while(true)
{
synchronized(howMany)
{
System.out.print("C");
howMany[2]++;
try
{
howMany.wait();
}
catch(InterruptedException e) {}
}
try {
sleep(3100);
}
catch(InterruptedException e) {}
}
}
public void ThD()
{
while(true)
{
synchronized(howMany)
{
System.out.print("D");
howMany[3]++;
try {
howMany.notify();
}
catch(IllegalMonitorStateException e) {}
}
try {
sleep(1000);
}catch(InterruptedException e) {}
}
}
public static void main(String[] args)
{
Klawiatura k = new Klawiatura();
k.start();
}
}
class Klawiatura extends Thread
{
int n;
static void ustaw(int t)
{
switch (t)
{
case 0: Th.end[0] = false;
case 1: Th.end[1] = false;
case 2: {Th.end[0] = false;Th.end[1] = false;}
}
}
public void run()
{
BufferedReader i = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("podaj liczbe\n1 - Koniec A, B\n2 - Koniec C D\n3
- Koniec wszystkie: ");
Th Th1 = new Th(1);
Th Th2 = new Th(2);
Th Th3 = new Th(3);
Th Th4 = new Th(4);
Th1.start();
Th2.start();
Th3.start();
Th4.start();
while(true)
{
try
{
n = i.read();
System.out.println("N: "+n);
switch (n)
{
case 49:
{
System.out.println("Watki 1, 2: STOP");
Th1.interrupt();
}
case 50:
{
System.out.println("Watki 3, 4: STOP");
}
case 51:
{
System.out.println("Watki 1 -4: STOP");
}
}
}
catch(IOException e) {}
}
}
}