SlideShare a Scribd company logo
Лекция 2. «Многопоточность»
Java осень 2012 лекция 2
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();
}
public class MyClass extends MyAbstractClass implements MyInterface {
private int b = 1;
public int getB(){
return b;
}
public int getDif(){
return getA() - b;
}
}
public class MyClassChild extends MyClass implements Interface1, Interface2{
…
}
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();
}
Java осень 2012 лекция 2
static Class<T> forName(String className)
String getCanonicalName()
Fields[] getField(String name)
Class[] getInterfaces()
Method[] getMethods()
Constructor[] getConstructors()
public Class<?> getClass()
public String toString()
public boolean equals(Object obj)
public int hashCode()
protected Object clone()
Stack
Java осень 2012 лекция 2
Java осень 2012 лекция 2
Java осень 2012 лекция 2
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();
}
}
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){…}
Java осень 2012 лекция 2
Java осень 2012 лекция 2
Java осень 2012 лекция 2
Java осень 2012 лекция 2
Java осень 2012 лекция 2
Java осень 2012 лекция 2
Java осень 2012 лекция 2
Java осень 2012 лекция 2
Java осень 2012 лекция 2
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();
}
}
public class HelloThread extends Thread {
public void run() {
System.out.println("Hello from a thread!");
}
public static void main(String args[]) {
(new HelloThread()).start();
}
}
Java осень 2012 лекция 2
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;
}
}
public class HelloThread extends Thread {
public void run() {
System.out.println("Hello from a thread!");
}
public static void main(String args[]) {
Thread thread = new HelloThread();
thread.start();
thread.join();
System.out.println("Hello from the main!");
}
}
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();
thread.start();
builder.append("Hello from the main!");
}
}
public synchronized void increment() {
j++;
}
public void addName(String name) {
synchronized(lockObject) {
lastName = name;
nameCount++;
}
nameList.add(name);
}
public class TwoMonitors {
private long c1 = 0;
private long c2 = 0;
private Object lock1 = new Object();
private Object lock2 = new Object();
public void c1Up() {
synchronized(lock1) {
c1++;
}
}
public void c2Up() {
synchronized(lock2) {
c2++;
}
}
}
public void c1c2Up() {
synchronized(lock1) {
c1++;
synchronized(lock2) {
c2++;
}
}
}
public void c2c1Up() {
synchronized(lock2) {
c2++;
synchronized(lock1) {
c1++;
}
}
}
private boolean needDoSomething;
public void run() {
while(true){
if(needDoSomething){
doSomething();
}
Thread.sleep(1000);
}
}
Java осень 2012 лекция 2
Java осень 2012 лекция 2
Java осень 2012 лекция 2

More Related Content

PPTX
#5 (Remote Method Invocation)
PPTX
Java весна 2013 лекция 2
PPTX
Multithreaded programming
PDF
DCN Practical
ODP
Jersey Guice AOP
PPTX
Multi threading
PDF
Core java pract_sem iii
PDF
ikh331-06-distributed-programming
#5 (Remote Method Invocation)
Java весна 2013 лекция 2
Multithreaded programming
DCN Practical
Jersey Guice AOP
Multi threading
Core java pract_sem iii
ikh331-06-distributed-programming

What's hot (20)

PDF
MySQL User Conference 2009: Python and MySQL
PDF
The Ring programming language version 1.7 book - Part 7 of 196
PDF
concurrency with GPars
PDF
Java Concurrency Gotchas
PDF
3. Объекты, классы и пакеты в Java
PPT
Socket Programming
PPT
Psycopg2 postgres python DDL Operaytions (select , Insert , update, create ta...
PDF
망고100 보드로 놀아보자 19
PDF
Gabriele Petronella - FP for front-end development: should you care? - Codemo...
PDF
groovy databases
PDF
5. Ввод-вывод, доступ к файловой системе
ODP
GPars (Groovy Parallel Systems)
DOCX
Java practical
ODP
Java Concurrency
PDF
Ruby basics
PDF
Developing Applications with MySQL and Java for beginners
PDF
Modern C++ Concurrency API
PDF
The Ring programming language version 1.5.2 book - Part 28 of 181
DOCX
PPTX
分散式系統
MySQL User Conference 2009: Python and MySQL
The Ring programming language version 1.7 book - Part 7 of 196
concurrency with GPars
Java Concurrency Gotchas
3. Объекты, классы и пакеты в Java
Socket Programming
Psycopg2 postgres python DDL Operaytions (select , Insert , update, create ta...
망고100 보드로 놀아보자 19
Gabriele Petronella - FP for front-end development: should you care? - Codemo...
groovy databases
5. Ввод-вывод, доступ к файловой системе
GPars (Groovy Parallel Systems)
Java practical
Java Concurrency
Ruby basics
Developing Applications with MySQL and Java for beginners
Modern C++ Concurrency API
The Ring programming language version 1.5.2 book - Part 28 of 181
分散式系統
Ad

Viewers also liked (8)

PDF
Алгоритмы и структуры данных осень 2013 лекция 7
PPT
Web весна 2012 лекция 9
PPT
Web осень 2012 лекция 1
PPTX
Java осень 2012 лекция 8
PPTX
Highload осень 2012 лекция 3
PPTX
СУБД осень 2012 Лекция 3
PPTX
СУБД осень 2012 лекция 9
PPTX
СУБД осень 2012 лекция 6
Алгоритмы и структуры данных осень 2013 лекция 7
Web весна 2012 лекция 9
Web осень 2012 лекция 1
Java осень 2012 лекция 8
Highload осень 2012 лекция 3
СУБД осень 2012 Лекция 3
СУБД осень 2012 лекция 9
СУБД осень 2012 лекция 6
Ad

Similar to Java осень 2012 лекция 2 (20)

PPTX
Java concurrency
PDF
От Java Threads к лямбдам, Андрей Родионов
PPTX
Concurrency in Programming Languages
PPTX
Programming Java - Lection 07 - Puzzlers - Lavrentyev Fedor
PDF
Loom and concurrency latest
PPT
Java concurrency begining
PPTX
Fork and join framework
ODP
Concurrent Programming in Java
PDF
Java Runtime: повседневные обязанности JVM
PDF
Concurrencyproblem
PPTX
Effective java - concurrency
PPTX
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
PPT
Java util concurrent
PDF
Java APIs- The missing manual (concurrency)
DOCX
Methods Of Thread Class
PDF
Time Travel - Predicting the Future and Surviving a Parallel Universe - JDC2012
ODP
Pick up the low-hanging concurrency fruit
PDF
Java 7 LavaJUG
PDF
От Java Threads к лямбдам, Андрей Родионов
PDF
Java concurrency
Java concurrency
От Java Threads к лямбдам, Андрей Родионов
Concurrency in Programming Languages
Programming Java - Lection 07 - Puzzlers - Lavrentyev Fedor
Loom and concurrency latest
Java concurrency begining
Fork and join framework
Concurrent Programming in Java
Java Runtime: повседневные обязанности JVM
Concurrencyproblem
Effective java - concurrency
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
Java util concurrent
Java APIs- The missing manual (concurrency)
Methods Of Thread Class
Time Travel - Predicting the Future and Surviving a Parallel Universe - JDC2012
Pick up the low-hanging concurrency fruit
Java 7 LavaJUG
От Java Threads к лямбдам, Андрей Родионов
Java concurrency

More from Technopark (20)

PDF
Лекция 11. Вычислительная модель Pregel
PDF
Лекция 14. Hadoop в Поиске Mail.Ru
PDF
Лекция 13. YARN
PDF
Лекция 12. Spark
PDF
Лекция 10. Apache Mahout
PDF
Лекция 9. ZooKeeper
PDF
Лекция 7. Введение в Pig и Hive
PDF
Лекция 6. MapReduce в Hadoop (графы)
PDF
Лекция 5. MapReduce в Hadoop (алгоритмы)
PDF
Лекция 4. MapReduce в Hadoop (введение)
PDF
Лекция 3. Распределённая файловая система HDFS
PDF
Лекция 2. Основы Hadoop
PDF
Лекция 1. Введение в Big Data и MapReduce
PPTX
СУБД 2013 Лекция №10 "Нереляционное решение в области баз данных — NoSQL"
PPT
СУБД 2013 Лекция №10 "Нереляционное решение в области баз данных — NoSQL" Час...
PPTX
СУБД 2013 Лекция №9 "Безопасность баз данных"
PPTX
СУБД 2013 Лекция №8 "Конфигурирование базы данных"
PPTX
СУБД 2013 Лекция №7 "Оптимизация запросов и индексирование"
PPTX
СУБД 2013 Лекция №5 "Определение узких мест"
PPTX
СУБД 2013 Лекция №6 "Профилирование запросов. Сложноструктурированные SQL-зап...
Лекция 11. Вычислительная модель Pregel
Лекция 14. Hadoop в Поиске Mail.Ru
Лекция 13. YARN
Лекция 12. Spark
Лекция 10. Apache Mahout
Лекция 9. ZooKeeper
Лекция 7. Введение в Pig и Hive
Лекция 6. MapReduce в Hadoop (графы)
Лекция 5. MapReduce в Hadoop (алгоритмы)
Лекция 4. MapReduce в Hadoop (введение)
Лекция 3. Распределённая файловая система HDFS
Лекция 2. Основы Hadoop
Лекция 1. Введение в Big Data и MapReduce
СУБД 2013 Лекция №10 "Нереляционное решение в области баз данных — NoSQL"
СУБД 2013 Лекция №10 "Нереляционное решение в области баз данных — NoSQL" Час...
СУБД 2013 Лекция №9 "Безопасность баз данных"
СУБД 2013 Лекция №8 "Конфигурирование базы данных"
СУБД 2013 Лекция №7 "Оптимизация запросов и индексирование"
СУБД 2013 Лекция №5 "Определение узких мест"
СУБД 2013 Лекция №6 "Профилирование запросов. Сложноструктурированные SQL-зап...

Recently uploaded (20)

PDF
Machine learning based COVID-19 study performance prediction
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Approach and Philosophy of On baking technology
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PPTX
A Presentation on Artificial Intelligence
PDF
Empathic Computing: Creating Shared Understanding
PPT
Teaching material agriculture food technology
PDF
Unlocking AI with Model Context Protocol (MCP)
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PPTX
Big Data Technologies - Introduction.pptx
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
KodekX | Application Modernization Development
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Machine learning based COVID-19 study performance prediction
Understanding_Digital_Forensics_Presentation.pptx
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Chapter 3 Spatial Domain Image Processing.pdf
The Rise and Fall of 3GPP – Time for a Sabbatical?
Spectral efficient network and resource selection model in 5G networks
Approach and Philosophy of On baking technology
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
A Presentation on Artificial Intelligence
Empathic Computing: Creating Shared Understanding
Teaching material agriculture food technology
Unlocking AI with Model Context Protocol (MCP)
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
NewMind AI Weekly Chronicles - August'25 Week I
Big Data Technologies - Introduction.pptx
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
The AUB Centre for AI in Media Proposal.docx
KodekX | Application Modernization Development
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...

Java осень 2012 лекция 2

  • 3. 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(); }
  • 4. public class MyClass extends MyAbstractClass implements MyInterface { private int b = 1; public int getB(){ return b; } public int getDif(){ return getA() - b; } } public class MyClassChild extends MyClass implements Interface1, Interface2{ … }
  • 5. 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(); }
  • 7. static Class<T> forName(String className) String getCanonicalName() Fields[] getField(String name) Class[] getInterfaces() Method[] getMethods() Constructor[] getConstructors()
  • 8. public Class<?> getClass() public String toString() public boolean equals(Object obj) public int hashCode() protected Object clone()
  • 13. 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(); } }
  • 14. 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){…}
  • 24. 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(); } }
  • 25. public class HelloThread extends Thread { public void run() { System.out.println("Hello from a thread!"); } public static void main(String args[]) { (new HelloThread()).start(); } }
  • 27. 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; } }
  • 28. public class HelloThread extends Thread { public void run() { System.out.println("Hello from a thread!"); } public static void main(String args[]) { Thread thread = new HelloThread(); thread.start(); thread.join(); System.out.println("Hello from the main!"); } }
  • 29. 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(); thread.start(); builder.append("Hello from the main!"); } }
  • 30. public synchronized void increment() { j++; } public void addName(String name) { synchronized(lockObject) { lastName = name; nameCount++; } nameList.add(name); }
  • 31. public class TwoMonitors { private long c1 = 0; private long c2 = 0; private Object lock1 = new Object(); private Object lock2 = new Object(); public void c1Up() { synchronized(lock1) { c1++; } } public void c2Up() { synchronized(lock2) { c2++; } } }
  • 32. public void c1c2Up() { synchronized(lock1) { c1++; synchronized(lock2) { c2++; } } } public void c2c1Up() { synchronized(lock2) { c2++; synchronized(lock1) { c1++; } } }
  • 33. private boolean needDoSomething; public void run() { while(true){ if(needDoSomething){ doSomething(); } Thread.sleep(1000); } }