23 Aralık 2019 Pazartesi

Java Page Turning Question

Brie’s Drawing teacher asks her class to open their books to a page number. Brie can either start turning pages from the front of the book or from the back of the book. She always turns pages one at a time. When she opens the book, page  is always on the right side:
image
When she flips page , she sees pages  and . Each page except the last page will always be printed on both sides. The last page may only be printed on the front, given the length of the book. If the book is  pages long, and she wants to turn to page , what is the minimum number of pages she will turn? She can start at the beginning or the end of the book.
Given  and , find and print the minimum number of pages Brie must turn in order to arrive at page .
Function Description
Complete the pageCount function in the editor below. It should return the minimum number of pages Brie must turn.
pageCount has the following parameter(s):
  • n: the number of pages in the book
  • p: the page number to turn to
Input Format
The first line contains an integer , the number of pages in the book.
The second line contains an integer, , the page that Brie's teacher wants her to turn to.

Sample Input 0
6
2
Sample Output 0
1
Explanation 0
If Brie starts turning from page , she only needs to turn  page:
Untitled Diagram(6).png
If Brie starts turning from page , she needs to turn  pages:
Untitled Diagram(3).png
Because we want to print the minumum number of page turns, we print  as our answer.
Sample Input 1
5
4
Sample Output 1
0
Explanation 1
If Brie starts turning from page , she needs to turn  pages:
Untitled Diagram(4).png
If Brie starts turning from page , she doesn't need to turn any pages:
Untitled Diagram(5).png
Because we want to print the minimum number of page turns, we print  as our answer.

Cozum : 
total = n/2
right = p/2
left = total - right
min (right, left)

static int pageCount(int n, int p) {
/*
* Write your code here.
*/
return Math.min(p/2, n/2 - p/2);

}

22 Aralık 2019 Pazar

Java Sorting

ID, FirstName, and CGPA bilgileri olan student listesi verilmis olsun. Bizim amacimiz CGPA lerini azalan sirada siralamak. Eger 2 ogrencinin CGPA leri esitse o zaman firstnamelerini alfabetik siraya gore siralayalim. Eger ayni isimlere sahiplerse ID lerine gore siralayalim. Her ogrencinin farkli ID si oldugu icin sorun olmaz. 
Ornek Input 

5
33 Rumpa 3.68
85 Ashis 3.85
56 Samiha 3.75
19 Samara 3.75

22 Fahim 3.76

Output

Ashis
Fahim
Samara
Samiha

Rumpa

Burada 5 kac tane input olacagi.

Bu soruya asagidaki koddaki boslugu tamamlayalim.

import java.util.*;
class Student{
 private int id;
 private String fname;
 private double cgpa;
 public Student(int id, String fname, double cgpa) {
  super();
  this.id = id;
  this.fname = fname;
  this.cgpa = cgpa;
 }
 public int getId() {
  return id;
 }
 public String getFname() {
  return fname;
 }
 public double getCgpa() {
  return cgpa;
 }
}

//Complete the code
public class Solution
{
 public static void main(String[] args){
  Scanner in = new Scanner(System.in);
  int testCases = Integer.parseInt(in.nextLine());
  
  List studentList = new ArrayList();
  while(testCases>0){
   int id = in.nextInt();
   String fname = in.next();
   double cgpa = in.nextDouble();
   
   Student st = new Student(id, fname, cgpa);
   studentList.add(st);
   
   testCases--;
  }
      
        Collections.sort(studentList, Comparator.comparing(Student :: getCgpa).reversed().
              thenComparing(Student :: getFname).thenComparing(Student :: getId)); 

       for(Student st: studentList){
   System.out.println(st.getFname());
  }
 }
}

1 Aralık 2019 Pazar

K - Largest Element of Array

Asagidaki soruda yapmamiz istenen verilen arraydaki k largest elementi bulmak.

Ornegin

arr[] = [3, 2, 1, 5, 6, 4], ve k =2 icin once siralayalim

1 2 3 4 5 6. burdaki en buyuk 2. eleman 5 oldugu icin output 5 olmalidir.

Cozume gecelim.

Nasil cozeriz :
 Once siralariz. Sonra da sondan k. elemani buluruz.

import java.util.Arrays;
import java.util.PriorityQueue;
public class KLargestElement {
 public static int kLargest(int[] arr, int k) {
  Arrays.sort(arr);
  return arr[arr.length - k];  
 } 
 public static void main(String[] args) {
  int arr[] = new int[] {3, 2, 1, 5, 6, 4};
  System.out.println(kLargest(arr, 2));
  
  int arr2[] = new int[] {3, 2, 3, 1, 2, 4, 5, 5, 6};
  System.out.println(kLargest(arr2, 4));
 }
}

Burda once siraladik sonra da sondan k. elemani bulduk. Islemin time completixy si O(nlogn) dir. Cunku siralama yaptigimiz icin .

Daha effektif yapmaya calisalim. Bunun icin heap kullanalim.

Elemanlari tek tek heap e eklerken, eger heap in size i k den buyukse ilk elemani cikaralim. Bu sekilde yaptigimizda elimizde en son k eleman kalmis olur. Bizde ilk elemani dondurursek o eleman k largest elemanimiz olur.

import java.util.Arrays;
import java.util.PriorityQueue;
public class KLargestElement {
 public static int kLargest(int[] arr, int k) {
  PriorityQueue<Integer> minHeap = new PriorityQueue<Integer>();
  for(int num : arr) {
    minHeap.add(num);
    if(minHeap.size() > k) {
     minHeap.remove();
    }
  }
  return minHeap.remove();
 } 
 public static void main(String[] args) {
  int arr[] = new int[] {3, 2, 1, 5, 6, 4};
  System.out.println(kLargest(arr, 2));
         int arr2[] = new int[] {3, 2, 3, 1, 2, 4, 5, 5, 6};
  System.out.println(kLargest(arr2, 4));
 }
}

Burada array i sort etmiyoruz. Heap kullaniyoruz. Burda ise time O(n) dir.

Validate String with Paranthesis

Verilen string imizde acilan parantezlerin sirayla kapanip kapanmadigini kontrol etmek istiyoruz.

Ornegin:

abc(){}[] => bu bizim gecerlidir. cunku acilan parantezler sirayla kapanmistir.

({)} => Bu ise gecersizdir. cunku { kapanmadan ( kapanmis.

Bunun icin izlememiz gereken yol su olmalidir.

Oncelikle acik parantezlerin ne oldugunu bir set te tanimladim ki o anki characterimin acik parantez oldugunu kontrol edebileyim. Eger acik parantezse bunu stack e ekliyorum. (Bu sekilde en son hangi parantez acildi kontrol edebilecegim)

Daha sonra kapali parantezler ve onlarin acik karsiliklarini bir mapte tanimliyorum. Bu sekilde eger o anki elemanim kapali parantezse bunun acik karsiligini buluyorum, ve stackteki son elemanla karsilastiriyorum. ornegin o anki elemanim ] ise bunun acik karsiligini mapten [ olarak buldum. Simdi ise stack in en ustundeki elemani pop ediyorum. [ mu diye kontrol ediyorum, eger degilse duzgun kapanmamistir. false dondurup bitiriyorum.

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.Stack;

public class ValidateParanthesisString {

 public static boolean isValidParanthesis(String str) {
  Map<Character, Character> closedMap = new HashMap();
  
  closedMap.put(')', '(');
  closedMap.put('}', '{');
  closedMap.put(']', '[');
  
  Set<Character> openParanthesis = new HashSet();
  openParanthesis.add('{');
  openParanthesis.add('[');
  openParanthesis.add('(');
  Stack<Character> openParanthesisStack = new Stack();
  
  for(int i=0; i< str.length(); i++) {
   if(openParanthesis.contains(str.charAt(i))) {
    openParanthesisStack.push(str.charAt(i));
   }
   if(closedMap.containsKey(str.charAt(i))) {
    if(!openParanthesisStack.pop().equals(closedMap.get(str.charAt(i)))) {
     return false;
    }
   }
  }
  return true;  
 } 
 public static void main(String[] args) {
  String str = "({)}";
  System.out.println(isValidParanthesis(str));
  String str2 = "abc() {}[]";
  System.out.println(isValidParanthesis(str2));
 }
}

Output: false true


Common Element of Three Array in Java

Elimizde 3 tane array olsun ve bunlardaki ortak elemanlari bulmak isteyelim.

Input
arr1 = [2, 6, 9, 11, 13, 17]
arr2 = [3, 6, 7, 10, 13, 18]
arr3 = [4, 5, 6, 9,  11,  13]

Output: [6, 13]

Burda izleyecegimiz yol soyle olmali:

x: arr1 in o anki elemani
y: arr2 nin o anki elemani
z: arr3 un o anki elemani

x,y ve z esit mi diye kontrol edecegiz. esitlerse arraya o anki elemani eklicez. ve herbirini 1 arttircaz
eger x, yden kucukse xi bir sonraki elemana atayacagiz.
y, zden kucukse y yi bir sonraki elemana atayacagiz
hic biri degilse zyi bir sonraki elemana atayacagiz


import java.util.ArrayList;
import java.util.List;
public class FindIntersection {
 public static List<Integer> intersection(int[] arr1, int[] arr2, int[] arr3) {
  List<Integer> commonElements = new ArrayList<Integer>();
  int x = 0, y = 0, z = 0;
  while (x < arr1.length && y < arr1.length && z < arr1.length) {
   if (arr1[x] == arr2[y] && arr1[x] == arr3[z]) {
    commonElements.add(arr1[x]);
    x++;
    y++;
    z++;
   } else {
    if (arr1[x] < arr2[y]) {
     x++;
    } else if (arr2[y] < arr3[z]) {
     y++;
    } else {
     z++;
    }
   }
  }
  return commonElements;
 }
 public static void main(String[] args) {
  int arr1[] = new int[] { 2, 6, 9, 11, 13, 17 };
  int arr2[] = new int[] { 3, 6, 7, 10, 13, 18 };
  int arr3[] = new int[] { 4, 5, 6, 9, 11, 13 };

  System.out.println(intersection(arr1, arr2, arr3));
 }
}

30 Kasım 2019 Cumartesi

Java - equals() ve hashCode() Methodları

Bu yazimda equals() ve hashCode() methodlarinin ne ise yaradigini gorecegiz. Oncelikle asagidaki ornek uzerinden gidelim.

import java.util.HashMap;
import java.util.Map;
public class Example {
 public static void main(String[] args) {
  Person p1 = new Person(1);
  Person p2 = new Person(1);

  Map<Person, String> pMap = new HashMap<Person, String>();
  pMap.put(p1, "Jon");
  pMap.put(p2, "Jon");
  
  System.out.println(pMap.size());
  
  Integer i1 = new Integer(1);
  Integer i2 = new Integer(1);
  Map<Integer, String> iMap = new HashMap<Integer, String>();
  
  iMap.put(i1, "1");
  iMap.put(i2, "1");
  
  System.out.println(iMap.size());
 }
}

class Person{
 int id;
 
 public Person(int id) {
  this.id = id;
 }
}

Ornegimizi aciklamaya calisalim. Person adinda id si olan bir classimiz var. Ve ben main classimda bir ayni id li iki ayri Person objesi olusturuyorum ve bunlari map e ekliyorum, soru ise map in size i nedir.

Ayni seyi Integer icin de yapiyoruz. Ayni degerli iki ayri integer objesi olusturuyoruz ve bir map olusturup bu iki integer i ekliyoruz. Ikisi de ayni degeri iceriyor. Ayni sekilde size i print ettiryoruz.

Sonucun ne olmasini bekleriz.

Output:
2
1

Yani person Map te ayni degeri icermesine ragmen size 2 dondu ama integer map te ayni degeri icerdigi icin 1 dondu. Bu nasil oldu.


Aciklama

Integer bir Wrapper class ve icerisinde hashCode ve equals metodlari tanimli olarak geliyor. O yuzden hashCode ve equals methodlari calistigi icin ayni degeri yeniden eklememize izin vermedi.

Ama Person classini biz yazdik ve icinde hashCode ve equals methodlari yok. Bu yuzden de bir kontrol yapmadi ve ayni degerleri ekleyebildik. Olmasi gereken once hashCode degerleri esit mi diye bakacak esitse equals methodu ile contentleri esit mi diye bakacak.

O yuzden Person classina hashCode() ve equals() methodlarini ekleyelim. Istersek kendimiz yazabiliriz istersek IDE den implement edebiliriz.

package com.examples;

import java.util.HashMap;
import java.util.Map;

public class Example {

 public static void main(String[] args) {
  Person p1 = new Person(1);
  Person p2 = new Person(1);
  
  Map pMap = new HashMap();
  pMap.put(p1, "Jon");
  pMap.put(p2, "Jon");
  
  System.out.println(pMap.size());
  
  Integer i1 = new Integer(1);
  Integer i2 = new Integer(1);
  Map iMap = new HashMap();
  
  iMap.put(i1, "1");
  iMap.put(i2, "1");
  
  System.out.println(iMap.size());
 }
}

class Person{
 int id;
 
 public Person(int id) {
  this.id = id;
 }
 @Override
 public int hashCode() {
  final int prime = 31;
  int result = 1;
  result = prime * result + id;
  return result;
 }
 @Override
 public boolean equals(Object obj) {
  if (this == obj)
   return true;
  if (obj == null)
   return false;
  if (getClass() != obj.getClass())
   return false;
  Person other = (Person) obj;
  if (id != other.id)
   return false;
  return true;
 } 
}

Bu durumda output ikisi icinde 1 olacak. hashCode ve equals methodlari sayesinde ayni degeri eklememize izin vermeyecek.



24 Kasım 2019 Pazar

LinkedList Insert / Insert Given Position / Print List


public class AddPositiontoNode {
 Node head;
 static class Node {
  Node next;
  int data;
  Node(int d) {
   this.data = d;
  }
 }
 public static AddPositiontoNode insertNode(AddPositiontoNode list, int d) {
  Node newNode = new Node(d);
  newNode.next = null;
  if (list.head == null) {
   list.head = newNode;
  } else {
   Node currNode = list.head;
   while (currNode.next != null) {
    currNode = currNode.next;
   }
   if (currNode.next == null) {
    currNode.next = newNode;
   }
  }
  return list;
 }
 public static AddPositiontoNode insertGivenPosition(AddPositiontoNode node, int position, int data) {
  Node newNode = new Node(data);
  int index = 1;
  Node currNode = node.head;
  if (position == 1) {
   newNode.next = node.head.next;
   node.head = newNode;
  } else {
   while (index + 1 != position) {
    index++;
    currNode = currNode.next;
   }
   if (index + 1 == position) {
    newNode.next = currNode.next;
    currNode.next = newNode;
   } else {
    newNode.next = currNode.next;
    currNode.next = newNode;
   }
  }
  return node;
 }
 public static void printList(Node head) {
  Node currNode = head;
  while (currNode != null) {
   System.out.println(currNode.data);
   currNode = currNode.next;
  }
 }
 public static void main(String[] args) {
  AddPositiontoNode node = new AddPositiontoNode();
  node = insertNode(node, 1);
  node = insertNode(node, 2);
  node = insertNode(node, 4);
  node = insertNode(node, 5);

  printList(node.head);
  System.out.println("---------------------");
  node = insertGivenPosition(node, 3, 3);
  printList(node.head);
 }
}

Output :

1
2
4
5
---------------------
1
2
3
4
5

17 Kasım 2019 Pazar

Thread Safety HashMap

Merhaba,
Bu yazida thread safe hashmap ile ilgili ornek yapacagiz.
Once thread safe olmayan bir ornek yapalim.

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class UnsafeMap {
 public static void main(String[] args) throws InterruptedException {
  Map cricketMap = new HashMap();
  cricketMap.put("Australia", 349);
  cricketMap.put("India", 257);
  ExecutorService executorService = Executors.newFixedThreadPool(10);
  Runnable task = new Runnable() {
   @Override
   public void run() {
    incrementScore(cricketMap, "India");
   }
  };
  for(int i=0; i<100 :="" ap="" cricketmap.get="" executorservice.awaittermination="" executorservice.shutdown="" executorservice.submit="" i="" inal="" incrementscore="" india="" integer="" is="" ndia="" of="" private="" score="" static="" system.out.println="" task="" timeunit.seconds="" tring="" void=""> teamMap, String team) {
  Integer score = teamMap.get(team);
  teamMap.put(team, score +1);
 }
}

Yukaridaki ornekte India nin score unu 100 arttirdik. Sonucun 258 olmasini bekliyoruz ama her seferinde baska sonuc cikiyor.

Final score of India is : 353
Final score of India is : 352

gibi. Neden ?

Cunku 

since multiple threads try to modify the HashMap concurrently, the change done by one thread gets overridden by some other thread, and the output becomes non-deterministic.

Bunu onlemek icinse ornegimizi thread safe yapalim. Yani sadece ayni anda tek bir thread erisebilsin. Bunun icin yapacagimiz iki sey sunlar olmali :

  • Use the Collections.synchronizedMap() method to obtain a synchronized view of the HashMap.
  • Write the increment logic inside a synchronized block.
Son halde kodumuz su sekilde olur:

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class Safemap {
 public static void main(String[] args) throws InterruptedException {
  Map cricketScore = Collections.synchronizedMap(new HashMap());  
  cricketScore.put("Turkey", 52);
  cricketScore.put("Germany", 170);   
  //we are creating thread pool with size 10
  ExecutorService executorService = Executors.newFixedThreadPool(10);
  
  Runnable task = new Runnable() {   
   @Override
   public void run() {
    incrementScore(cricketScore, "Turkey");    
   }
  };
  for(int i=0; i<100 :="" ap="" cricketscore.get="" executorservice.awaittermination="" executorservice.shutdown="" executorservice.submit="" i="" inal="" incrementscore="" integer="" is="" of="" private="" score="" static="" system.out.println="" task="" timeunit.seconds="" tring="" turkey="" urkey="" void=""> scoreMap, String team) {
  synchronized (scoreMap) {
   Integer score = scoreMap.get(team);
   scoreMap.put(team, score +1);
  }
 }
}
Turkiyenin score unu 100 arttirdik. Threas safe oldugu icin her zaman 152 donecektir.

Final score of Turkey is : 152

14 Kasım 2019 Perşembe

Interthread Communication


Asagidaki ornegi incelemeye baslayalim.

Oncelik A adli bir classimiz var. Setleme ve getleme yapmasi icin put ve get methodlarimiz var. Her 2 methodumuz da degerlerimizi anlik olarak yazdirdik.

Daha sonra ise Producer ve Consumer adli classlarimiz var. Producer deger setlemek Consumer ise getlemek icin. Producer icinde sonsuz bir dongu var ve her seferinde degeri +1 i olarak setliyor.

Consumer icinde de sonsuz bir dongu var ve degeri get ediyor. Bu islemleri run() methodu icinde yapiyoruz. Bu run methodunun cagirilmasi icinse Thread e ihtiyacimiz var. O yuzden constuctor icinde thread olusturuyoruz ve start methodunu cagiriyoruz cunku start() methodu run i cagiracaktir.


class A{
 int num;
 // we need two methods here. one for set value and one for get the value
 public void put(int num) {
  System.out.println("Put : "+ num);
  this.num = num;
 } 
 public void get() {
  System.out.println("Get : "+ num);
 }
}
class Producer implements Runnable{ 
 A a;  
 public Producer(A a){
  this.a = a;
  // for Producer to call run method we need to create Thread. with start method, it will call run  
  Thread t = new Thread(this, "Producer");
  t.start();
 }
 public void run() {
  int i=0;
  // we have infinite loop here. every loop we set the value as i++
  while(true) {
   a.put(i++);
   try { Thread.sleep(1000); } catch(Exception e) {}
  }
 }
}
class Consumer implements Runnable{
 A a; 
 public Consumer(A a) {
  this.a = a;
  Thread t = new Thread(this, "Consumer");
  t.start();
 } 
 public void run() {
  while(true) {
   a.get();
   try { Thread.sleep(1000); } catch(Exception e) {}
  }
 }
}
public class ThreadCommunication {
 public static void main(String[] args) {
  A a = new A();
  new Producer(a);
  new Consumer(a);
 }}

Bunu calistirdigimiz da ise aldigimiz sonuca bakalim:
Put : 0
Get : 0
Get : 0
Put : 1
Put : 2
Get : 1
Put : 3
Get : 2
Put : 4
Get : 3
Put : 5
Get : 4


Gordugumuz gibi 0 icin 2 kez Get calismis. Bizim istedigimiz bu degildi. once setlesin sonra getlesin ve bu sirayla olsundu.


Bunun icin boolean bir degisken olusturacagiz ve default olarak false a setlicez.
put() icinde kontrol edelim. eger true ise yani zaten setlenmisse bizim setlememize gerek yok demektir. Bu durumda Consumer in degeri consume etmesini beklicez. Bunu wait() methodu ile yapicaz. Simdi su bilgiyi hatirlayalim.

Sleep() methodu kullandigimizda thread wait state ine gecer ve o sure bitince tekrar runnable olur. ama wait() ile oyle bir durum yok. Bekler surekli. Bu durumda bunu birilerine haber verelim ki bekledigini anlasin. Bunu notify() methodu ile yapariz.

Bunun icin haber vermemiz gereken consumer dur. Bunun icin setlendikten sonra notify() cagiriyoruz ve notify methodu consumer i notify edicek.

Simdi ayni islemleri get icin dusunelim. Eger valueSet degeri false gelirse deger setlenmemis demektir. Bu durumda setlenmemis degeri okuyamayiz. Beklememiz lazim. Kimi ? Producer i. yine wait cagirdik. Eger deger setlenmis ile okuyalim.

Ayrica wait() cagirdigimiz tum methodlarin synchronized olmasi zorundadir.
Kodumuzun son hali asagidaki gibi olacaktir.

Ayrica sleep surelerini de degistirdim. 0.5 saniyede setliyor ve consumer 2 saniyede okuyor. bu durumda consumer in okumasini beklicez, o okumadan asla setlemeye gecmicek.

class A{
 int num;
 // to keep track the value we created a boolean value
 boolean valueSet = false;
 // we need two methods here. one for set value and one for get the value
 public synchronized void put(int num) {
  while(valueSet) {
   // eger valueSet true ise deger zaten setlenmistir.
   // bir daha setlemeye gerek yok.
   // o yuzden burada beklicez yani wait cagiricaz
   // with wait method it will wait for consumer to consume the value
   
   try { wait(); } catch(Exception e) {}
  }  
  System.out.println("Put : "+ num);
  this.num = num;
  valueSet = true;
  notify();
 } 
 public synchronized void get() {
  while(!valueSet) {
   try { wait(); } catch(Exception e) {}
  }
  System.out.println("Get : "+ num);
  valueSet = false;
  notify();
 }
}
class Producer implements Runnable{ 
 A a;  
 public Producer(A a){
  this.a = a;
  // for Producer to call run method we need to create Thread. with start method, it will call run
  Thread t = new Thread(this, "Producer");
  t.start();
 }
 public void run() {
  int i=0;
  // we have infinite loop here. every loop we set the value as i++
  while(true) {
   a.put(i++);
   try { Thread.sleep(500); } catch(Exception e) {}
  }
 }
}
class Consumer implements Runnable{
 A a; 
 public Consumer(A a) {
  this.a = a;
  Thread t = new Thread(this, "Consumer");
  t.start();
 } 
 public void run() {
  while(true) {
   a.get();
   try { Thread.sleep(2000); } catch(Exception e) {}
  }
 }
}
public class ThreadCommunication {
 public static void main(String[] args) {
  A a = new A();
  new Producer(a);
  new Consumer(a);
 }}


Output:
Put : 0
Get : 0
Put : 1
Get : 1
Put : 2
Get : 2
Put : 3
Get : 3
Put : 4
Get : 4
Put : 5
Get : 5
Put : 6

9 Kasım 2019 Cumartesi

Multithreading Java

5 defa Hi, 5 defa Hello yazdiralim.



Output: Hi
Hi
Hi
Hi
Hi
Hello
Hello
Hello
Hello
Hello


Gordugumuz gibi 5 kez Hi ve Hello yazdi. Simdi ise her bir yazmadan once biraz beklesin diye bi thread sleep koyalim. 500 verdim yani 500 ms.




Kodumuz bu sefer yukaridaki gibi. 500 ms arayla print ediyor. Burada belirtmek istedigimiz sey kodumuz yine ayni seyi yapiyor ancak Hi yazmasinin bitmesini bekliyor. Bitmeden Hello ya gecmiyor. Bizim istedigimiz ise ikisi ayni anda calisabilsin, birbirini bloklamasin.

O yuzden burada thread kullanacagiz. Her classimiz Thread classini extend ederse classlarimiz Thread haline gelmis olur. Eee Thread classlarinda mutlaka run() olmali ki islemimiz orada calissin. O yuzden show() metodunu run() haline getiriyoruz. ve main threadimiz obj1.start() dememiz lazim. start() cagirdigimiz anda gidip run() methodunu calistirir.



Output  :
Hi
Hello
Hi
Hello
Hello
Hi
Hi
Hello
Hello
Hi

Gordugumuz gibi artik 2 thread birbirini beklemiyor ve ayni anda calisabiliyor. Hatta o kadar ayni ana denk gelmis ki ardarda 2 tane Hello goruyoruz. Ayni ana gelme durumlarinda schedular a gidilir ve schedular hangisi daha kisa ve kolaysa onu secer. Ancak burada 2 methodumuz da ayni islemi yaptigi icin random olarak Hello secilmis.


Interfacelerle Calismak

Javada asagidaki gibi bir kullanim yoktur.

class A extends B, C

Sadece bir tane extend edebiliriz.

O halde soyle bir sey yapmak yerine

class Ornek extends A, Thread { (hatali)

asagidaki gibi yapabiliriz.

class Ornek extends A implements Runnable {

Yani neymis : Thread olusturmanin 2 yontemi varmis.

1. extends Thread diyerek

2. implements Runnable diyerek

Hangisi isimizi gorurse onu kullanmaliyiz.

O halde ornegimizi bir de bu sekilde deneyelim.

Ancak artik classlarimiz Thread tipinde olmadigi icin obj1.start() diyemeyiz. Hata verir. Runnable da o sekilde bir method yok.

O zaman Thread olusturmamiz lazim.

Thread t1 = new Thread(obj1);
t1.start();

iste bu calisir. O halde kodumuzu duzenleyip yeniden deneyelim.



Output:
Hi
Hello
Hello
Hi
Hello
Hi
Hi
Hello
Hello
Hi

Lambda Expressions

Simdi de bu yazmis oldugumuz daha kisa ve daha efektif hale getirmeye calisalim.

Hi ve Hello adinda iki class yazdik ve ikisinin de yaptigi sey sadece Runnable i implement etmek. O halde bunlara gerek yok.Thread icinde de ayni islemi yapabiliriz.



Simdi de bunu lambda haline getirelim. Yani method isimlerine ve parantezlere gerek yok.

O durumda da soyle olur:


Son durumda ise kodumuz asagidaki gibi olur ve ayni islevi daha efektif olarak yapar.


Output:

Hi
Hello
Hello
Hi
Hi
Hello
Hi
Hello
Hi
Hello