Mam 2 klasy Exec1 i Exec2.
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Exec1 implements Runnable {
private Lock lock = new ReentrantLock();
@Override
public void run() {
try
{
lock.lockInterruptibly();
for(int i = 1; i <= 10; i ++)
{
System.out.println(i +":: ---- wątek: 1");
if(i==5)
{
System.out.println("blok");
}
}
}
catch(InterruptedException ex)
{
lock.unlock();
}
finally{
lock.unlock();
}
}
}
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Exec2 implements Runnable {
private Lock lock = new ReentrantLock();
@Override
public void run() {
try
{
lock.lockInterruptibly();
for(int i = 1; i <= 10; i ++)
{
//System.out.println(i +" OBLICZENIA:: ---- wątek: " + Thread.currentThread().getName());
System.out.println(i +":: ---- wątek: 2");
if(i==5)
{
System.out.println("blok");
}
}
}
catch(InterruptedException ex)
{
lock.unlock();
}
finally{
lock.unlock();
}
}
}
a takze main
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Start {
public static void main(String[] args) {
try
{
ExecutorService service = Executors.newFixedThreadPool(2);
Exec1 e1 = new Exec1();
Exec2 e2 = new Exec2();
service.execute(e1);
service.execute(e2);
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
Zwrot w konsoli to cos w rodzaju :
1:: ---- wątek: 1
1:: ---- wątek: 2
2:: ---- wątek: 1
2:: ---- wątek: 2
3:: ---- wątek: 1
3:: ---- wątek: 2
4:: ---- wątek: 2
5:: ---- wątek: 2
blok
6:: ---- wątek: 2
4:: ---- wątek: 1
7:: ---- wątek: 2
5:: ---- wątek: 1
blok
8:: ---- wątek: 2
9:: ---- wątek: 2
6:: ---- wątek: 1
10:: ---- wątek: 2
7:: ---- wątek: 1
8:: ---- wątek: 1
9:: ---- wątek: 1
10:: ---- wątek: 1
a chcialbym wynik:
1:: ---- wątek: 1
2:: ---- wątek: 1
3:: ---- wątek: 1
4:: ---- wątek: 1
5:: ---- wątek: 1
blok
1:: ---- wątek: 2
2:: ---- wątek: 2
3:: ---- wątek: 2
4:: ---- wątek: 2
5:: ---- wątek: 2
blok
6:: ---- wątek: 1
7:: ---- wątek: 1
8:: ---- wątek: 1
9:: ---- wątek: 1
10:: ---- wątek: 1
blok
6:: ---- wątek: 2
7:: ---- wątek: 2
8:: ---- wątek: 2
9:: ---- wątek: 2
10:: ---- wątek: 2
Wiem, ze musze użyć do tego synchronizacji lub zamkow/przerwan. Pomogl by mi ktos to zrozumiec. To wazne. Do poniedzialku musze to zrozumiec. Bedzie ktos dobry i to wytlumaczy, badz podesle jakies dobre tutoriale?
Nie chodzi o samo wykonanie polecenie, bo sam je sobie wysmylilem. To tylko przyklad.