Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Java весна 2013 лекция 2

323 views

Published on

Published in: Technology
  • Be the first to comment

  • Be the first to like this

Java весна 2013 лекция 2

  1. 1. public abstract class MyAbstractClass { private int a = 0; public int getSum(){ return a + getB(); } protected int getA(){ return a; } abstract int getB(); } public interface MyInterface { int getDif(); } MyAbstractClass <<abstract>> - int a + int getSum() + int getA() int getB() MyInterface <<interface>> int getDif()
  2. 2. public class MyClass extends MyAbstractClass implements MyInterface { private int b = 1; public int getB(){ return b; } public int getDif(){ return getA() - b; } } MyAbstractClass <<abstract>> MyInterface <<interface>> MyClass
  3. 3. public static void main(String[] args) { //MyAbstractClass aObject = new MyAbstractClass(); - ошибка MyClass object1 = new MyClass(); int result1 = object1.getSum(); int result2 = object1.getDif(); doSomething(object1); MyInterface object2 = new MyClass(); //int result3 = object2.getSum(); - ошибка int result4 = object2.getDif(); doSomething(object2); } public static void doSomething(MyInterface object){ //MyClass object3 = object; - ошибка //int result5 = object.getSum(); - ошибка int result6 = object.getDif(); }
  4. 4. public class MyClassChild extends MyClass implements Interface1, Interface2{ … } MyClass Interface2 <<interface>> MyClassChild Interface1 <<interface>>
  5. 5. ― static Class<T> forName(String className) String getCanonicalName() Fields[] getField(String name) Class[] getInterfaces() Method[] getMethods() Constructor[] getConstructors()
  6. 6. public Class<?> getClass() ― public String toString() public boolean equals(Object obj) public int hashCode() protected Object clone()
  7. 7. bits type type 8 byte boolean 16 short char 32 int float 64 long double
  8. 8.
  9. 9. List students == List<Object> students public Object getFirstValue(List listOfNumbers){ return listOfNumbers.get(0); } public String getFirstStringValue(List<String> listOfNumbers){ return listOfNumbers.get(0); } public static void main(String[] args){ List<Integer> listOfNumbers = new ArrayList<Integer>(); listOfNumbers.add(42); String name1 = (String)getFirstValue(listOfNumbers); //Runtime error! String name2 = getFirstStringValue(listOfNumbers); //Compile error! }
  10. 10. public class GenericExample<T> { private T value; public GenericExample(T value){ this.value = value; } public T getT(){ return value; } public static void main(String[] args) { GenericExample<Integer> intObject = new GenericExample<Integer>(1); Integer valueInteger = intObject.getT(); GenericExample<String> stringObject = new GenericExample<String>("word"); String valueString = stringObject.getT(); } }
  11. 11. public class GenericExample { public static <T> T getTheFirst(List<T> list){ return list.get(0); } public static void main(String[] args) { List<Integer> listOfInts = new ArrayList<Integer>(); listOfInts.add(0); Integer intValue = getTheFirst(listOfInts); List<String> listOfStrings = new ArrayList<String>(); listOfInts.add(“Java is the best!”); String stringValue = getTheFirst(listOfStrings); } }
  12. 12. public class LongId<T> { private long id; public LongId(long id){ this.id = id; } public long getLong(){ return id; } } public void manyIdsInParams(long userId, long serverId, long adress){…} public void manyIdsInParams(LongId<User> userId, LongId<Server> serverId, LongId<Adress> adress){…}
  13. 13.
  14. 14. public class HelloRunnable implements Runnable { public void run() { System.out.println("Hello from a thread!"); } public static void main(String args[]) { (new Thread(new HelloRunnable())).start(); } }
  15. 15. public class HelloThread extends Thread { public void run() { System.out.println("Hello from a thread!"); } public static void main(String args[]) { (new HelloThread()).start(); } }
  16. 16. try { Thread.sleep(5000); } catch (InterruptedException e) { // We've been interrupted. return; } for (int i = 0; i < inputs.length; i++) { heavyTask(inputs[i]); if (Thread.interrupted()) { // We've been interrupted. return; } }
  17. 17. public class HelloThread extends Thread { public void run() { System.out.println(“1. Hello from a thread!"); } public static void main(String args[]) { Thread thread = new HelloThread(); thread.start(); thread.join(); System.out.println(“2. Hello from the main!"); } }
  18. 18. public class HelloThread extends Thread { private StringBuilder builder; public HelloThread(StringBuilder builder){ this.builder = builder; } public void run() { builder.append(“?. Hello from a thread!"); } public static void main(String args[]) { StringBuilder builder = new StringBuilder(); Thread thread = new HelloThread(builder); thread.start(); builder.append(“?. Hello from the main!"); thread.join(); Systen.out.printin(builder.toString()); } }
  19. 19. public synchronized void increment() { j++; } public void addName(String name) { synchronized(lockObject) { lastName = name; nameCount++; } nameList.add(name); }
  20. 20. public class TwoMonitors { private long c1 = 0; private long c2 = 0; private Object lock1 = new Object(); //the first monitor private Object lock2 = new Object(); //the second monitor public void c1Up() { synchronized(lock1) { c1++; } } public void c2Up() { synchronized(lock2) { c2++; } } }
  21. 21. public void c1c2Up() { synchronized(lock1) { c1++; synchronized(lock2) { c2++; } } } public void c2c1Up() { synchronized(lock2) { c2++; synchronized(lock1) { c1++; } } }
  22. 22. private boolean needDoSomething; public void run() { while(true){ if(needDoSomething){ doSomething(); } Thread.sleep(1000); } }
  23. 23. ― ― ― ―
  24. 24. 4. class Object и class Class<?>. Основные методы этих классов 5. Простые типы в Java. Классы "обертки" простых типов. 6. Generic programming в Java. Создание своих шаблонных классов и методов. 7. Коллекции в Java. Iterator, Iterable. 8. Processes и Threads. 9. Interface Runnable. class Thread. Методы start() и run(). 10. Методы класса Thread: sleep(), interrupt(), join(). 11. Ключевые слова volatile и synchronized. 12. Проблемы многопоточного доступа к данным. Race condition. Deadlock. 13. Методы класса Object: wait(), notify() и notifyAll().
  25. 25. Шаг 4: Вынести Frontend из класса Main: class Frontend extends AbstractHandler implements Runnable{…} Шаг 5: Добавить в класс Frontend переменную handleCount = 0. Запустить Frontend в отдельном потоке. В методе run() писать значение handleCount в лог каждые 5 секунд. В методе handle() кроме формирования страницы, увеличивать значение handleCount. Hint: Для handleCount хорошо подходит тип данных AtomicInteger.

×