diff --git a/java/samples/introduction/A.java b/java/samples/introduction/A.java new file mode 100644 index 0000000..1b9e89d --- /dev/null +++ b/java/samples/introduction/A.java @@ -0,0 +1,39 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ + +package basic; + +/** + * + * @author (C)Y.D.Zakovryashin, 07.10.2022 + */ +public class A { + private A a; + private A b; + + public A () { + this(null); + System.out.println ("A::A()"); + } + + public A (A a) { + System.out.println("A::A(A)"); + } + + public void a () { + System.out.println("A::a()"); + } + + public void a (A a) { + System.out.println("A::a(A)"); + } + + public static void main (String[] args) { + System.out.println("Hello, Java!!!"); + A a = new A (null); + a.a(a); + } +} diff --git a/java/samples/introduction/B.java b/java/samples/introduction/B.java new file mode 100644 index 0000000..0c1d424 --- /dev/null +++ b/java/samples/introduction/B.java @@ -0,0 +1,29 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package basic; + +/** + * + * @author (C)Y.D.Zakovryashin, 07.10.2022 + */ +public class B extends A { + + public B() { + super(null); // this(); + System.out.println("B::B()"); + } + + public static void main(String[] args) { + B b = new B(); + b.a(); + } + + @Override + public void a() { + System.out.println("B::a()"); + super.a(); + } +} diff --git a/java/samples/introduction/C.java b/java/samples/introduction/C.java new file mode 100644 index 0000000..3fe6dca --- /dev/null +++ b/java/samples/introduction/C.java @@ -0,0 +1,28 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package basic; + +/** + * + * @author (C)Y.D.Zakovryashin, 07.10.2022 + */ +public class C implements I { + + public void a() { + System.out.println("C::a()"); + } + + public void a(A a) { + System.out.println("C::a(A)"); + } + + public static void main(String[] args) { + C c = new C(); + c.a(); + c.a(null); + c.b(); + } +} diff --git a/java/samples/introduction/DEV-J110.01. Основы ООП.pdf b/java/samples/introduction/DEV-J110.01. Основы ООП.pdf new file mode 100644 index 0000000..2b901cc Binary files /dev/null and b/java/samples/introduction/DEV-J110.01. Основы ООП.pdf differ diff --git a/java/samples/introduction/DEV-J110.02. Обзор платформы.pdf b/java/samples/introduction/DEV-J110.02. Обзор платформы.pdf new file mode 100644 index 0000000..90a617f Binary files /dev/null and b/java/samples/introduction/DEV-J110.02. Обзор платформы.pdf differ diff --git a/java/samples/introduction/DEV-J110.03. Классы.pdf b/java/samples/introduction/DEV-J110.03. Классы.pdf new file mode 100644 index 0000000..072f72e Binary files /dev/null and b/java/samples/introduction/DEV-J110.03. Классы.pdf differ diff --git a/java/samples/introduction/DEV-J110.04. Наследование классов.pdf b/java/samples/introduction/DEV-J110.04. Наследование классов.pdf new file mode 100644 index 0000000..565fefb Binary files /dev/null and b/java/samples/introduction/DEV-J110.04. Наследование классов.pdf differ diff --git a/java/samples/introduction/DEV-J110.05. Специальные виды классов.pdf b/java/samples/introduction/DEV-J110.05. Специальные виды классов.pdf new file mode 100644 index 0000000..92f73d3 Binary files /dev/null and b/java/samples/introduction/DEV-J110.05. Специальные виды классов.pdf differ diff --git a/java/samples/introduction/DEV-J110.06. Интерфейсы.pdf b/java/samples/introduction/DEV-J110.06. Интерфейсы.pdf new file mode 100644 index 0000000..110e7c1 Binary files /dev/null and b/java/samples/introduction/DEV-J110.06. Интерфейсы.pdf differ diff --git a/java/samples/introduction/I.java b/java/samples/introduction/I.java new file mode 100644 index 0000000..1fffaa4 --- /dev/null +++ b/java/samples/introduction/I.java @@ -0,0 +1,24 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package basic; + +/** + * + * @author (C)Y.D.Zakovryashin, 07.10.2022 + */ +public interface I { + + public static final A a = new A(null); + A b = null; + + public abstract void a(); + + void a(A a); + + default void b() { + System.out.println("I:b() - default"); + } +} diff --git a/java/samples/java-packages/DEV-J120.SE.4.1.AWT.pdf b/java/samples/java-packages/DEV-J120.SE.4.1.AWT.pdf new file mode 100644 index 0000000..793cd6b Binary files /dev/null and b/java/samples/java-packages/DEV-J120.SE.4.1.AWT.pdf differ diff --git a/java/samples/java-packages/source/DemoActionListener.java b/java/samples/java-packages/source/DemoActionListener.java new file mode 100644 index 0000000..8622188 --- /dev/null +++ b/java/samples/java-packages/source/DemoActionListener.java @@ -0,0 +1,35 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ + +package gui; + +import java.awt.Color; +import java.awt.Container; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +/** + * + * @author (C)Y.D.Zakovryashin, 28.11.2022 + */ +public class DemoActionListener implements ActionListener{ + + private Container cp; + private Color defaultColor; + + public DemoActionListener ( Container cp) { + this.cp = cp; + defaultColor = cp.getBackground(); + } + + @Override + public void actionPerformed(ActionEvent e) { + System.out.println ("Action performed"); + Color c = cp.getBackground(); + cp.setBackground(c == defaultColor ? Color.BLUE : defaultColor) ; + } + +} diff --git a/java/samples/java-packages/source/DemoCollection.java b/java/samples/java-packages/source/DemoCollection.java new file mode 100644 index 0000000..aba8662 --- /dev/null +++ b/java/samples/java-packages/source/DemoCollection.java @@ -0,0 +1,135 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package std; + +import java.io.Serializable; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +/** + * + * @author (C)Y.D.Zakovryashin, 05.12.2022 + */ +public class DemoCollection { + + public class User implements Serializable { + + private String login; + private String password; + + public User(String login, String password) { + this.login = login; + this.password = password; + } + + public String getLogin() { + return login; + } + + public void setLogin(String login) { + this.login = login; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + @Override + public String toString() { + return "User{" + "login=" + login + ", password=" + password + '}'; + } + } + + public class Info implements Serializable { + + String info; + + public Info(String info) { + this.info = info; + } + + public String getInfo() { + return info; + } + + public void setInfo(String info) { + this.info = info; + } + + @Override + public String toString() { + return "Info{" + "info=" + info + '}'; + } + } + + public static void main(String[] args) { + DemoCollection demo = new DemoCollection(); +// demo.print(demo.init(5)); + Map m = demo.init(); + demo.printMap(m); + } + + private Set init(int size) { + int[] ai = {123, 345, 4564, 345, 123}; + HashSet hs = new HashSet<>(); + for (int i : ai) { + System.out.println("Add " + i + " is " + + hs.add(new Integer(i))); + } + return hs; + } + + private Map init() { + HashMap hm = new HashMap<>(); + hm.put(new User("first", "12344"), new Info("first message")); + hm.put(new User("second", "283479"), new Info("secondt message")); + return hm; + } + + private void printIterator(Collection c) { + if (c == null || c.isEmpty()) { + System.out.println("Collection is null or empty"); + return; + } + Iterator i = c.iterator(); + while (i.hasNext()) { + T t = i.next(); + System.out.println(t); + } + } + + private void print(Collection c) { + if (c == null || c.isEmpty()) { + System.out.println("Collection is null or empty"); + return; + } + for (T t : c) { + System.out.println(t); + } + } + + private void printMap(Map m) { + // 1. Map.Entry + for (Map.Entry tm : m.entrySet()) { + System.out.println( tm.getKey() + " --> " + + tm.getValue()); + } + System.out.println("------------------------------"); + // 2. keySet -> get(...) + for (User u : m.keySet()) { + Info i = m.get(u); + System.out.println(u + " --> " + i); + } + } +} diff --git a/java/samples/java-packages/source/DemoFunInterface.java b/java/samples/java-packages/source/DemoFunInterface.java new file mode 100644 index 0000000..ce4a529 --- /dev/null +++ b/java/samples/java-packages/source/DemoFunInterface.java @@ -0,0 +1,24 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package std; + +/** + * + * @author (C)Y.D.Zakovryashin, 05.12.2022 + */ +@FunctionalInterface +public interface DemoFunInterface { + + public String message(int x); + + public static String info() { + return "Demo Functional interface"; + } + + default public void demo () { + System.out.println("Demo method"); + } +} diff --git a/java/samples/java-packages/source/DemoInteger.java b/java/samples/java-packages/source/DemoInteger.java new file mode 100644 index 0000000..c0da479 --- /dev/null +++ b/java/samples/java-packages/source/DemoInteger.java @@ -0,0 +1,25 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ + +package lang; + +/** + * + * @author (C)Y.D.Zakovryashin, 14.11.2022 + */ +public class DemoInteger { + public static void main(String[] args) { + Integer i = new Integer ("1234"); + Integer j = Integer.valueOf("12345", 7); + Integer k = ++i; + i = ++i; + String s = "asdf"; + s += "gth"; + String t = new String (s); + System.out.println("s: " + s); + System.out.println(k); + } +} diff --git a/java/samples/java-packages/source/DemoJFrame.java b/java/samples/java-packages/source/DemoJFrame.java new file mode 100644 index 0000000..76d84a3 --- /dev/null +++ b/java/samples/java-packages/source/DemoJFrame.java @@ -0,0 +1,63 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package gui; + +import java.awt.Container; +import java.awt.FlowLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JLabel; + +/** + * + * @author (C)Y.D.Zakovryashin, 28.11.2022 + */ +public class DemoJFrame extends JFrame { + + private JLabel lbl; + + public DemoJFrame(String title) { + super(title); +// setBounds (x, y, w, h); +// setTitle (title); + setLocation(120, 80); + setSize(640, 480); + setResizable(false); + setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); + init(); + setVisible(true); + } + + public static void main(String[] args) { + DemoJFrame demo = new DemoJFrame("Demo JFrame"); + } + + private void init() { +// DemoWindowListener wl = new DemoWindowListener(); +// addWindowListener(wl); + addWindowListener(new DemoWindowAdapter()); + Container cp = getContentPane(); + cp.setLayout(null); + // cp.setLayout(new FlowLayout(FlowLayout.CENTER, 10, 5)); + lbl = new JLabel("Demo label"); + lbl.setBounds(120, 80, 160, 32); + JButton b = new JButton("Demo button"); + b.setBounds(120, 140, 160, 32); + b.addActionListener(new DemoActionListener(cp)); + // class ? implements ActionListener { .... } + b.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + String s = lbl.getText(); + lbl.setText(s + "*"); + } + }); + cp.add(lbl); + cp.add(b); + } +} diff --git a/java/samples/java-packages/source/DemoLambda.java b/java/samples/java-packages/source/DemoLambda.java new file mode 100644 index 0000000..47ecf43 --- /dev/null +++ b/java/samples/java-packages/source/DemoLambda.java @@ -0,0 +1,52 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package std; + +import java.util.ArrayList; + +/** + * + * @author (C)Y.D.Zakovryashin, 05.12.2022 + */ +public class DemoLambda { + + public static void main(String[] args) { + DemoLambda demo = new DemoLambda(); + ArrayList al = demo.init(); + demo.print(al); + al.removeIf((Integer x) -> x % 2 != 0); + demo.print(al); + al.forEach((Integer x) -> { + System.out.print(x * 2 + ", "); + }); + System.out.println(""); + } + + private ArrayList init() { + int[] ai = {1, 2, 3, 4, 5, 6, 77, 78}; + ArrayList al = new ArrayList<>(); + for (int i : ai) { + al.add(i); + } + return al; + } + + private void a(int x) { + + // new ? implements DemoFunInterface { ... } + DemoFunInterface d = x1 -> { + return String.valueOf(x1); + }; + } + + private void print(ArrayList al) { + for (Integer i : al) { + System.out.print(i + ", "); + } + System.out.println(); + } + +} diff --git a/java/samples/java-packages/source/DemoObject.java b/java/samples/java-packages/source/DemoObject.java new file mode 100644 index 0000000..91a6a4f --- /dev/null +++ b/java/samples/java-packages/source/DemoObject.java @@ -0,0 +1,38 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package lang; + +/** + * + * @author (C)Y.D.Zakovryashin, 14.11.2022 + */ +public class DemoObject implements Cloneable { + private int id = 12344; + + public static void main(String[] args) { + DemoObject obj = new DemoObject(); + System.out.println("obj: " + obj.id); + try { + DemoObject clone = (DemoObject) obj.clone(); + System.out.println("clone: " + clone.id ); + DemoObject clone2 = (DemoObject) clone.clone(); + System.out.println("clone2: " + clone2.id ); + } catch (CloneNotSupportedException e) { + System.out.println("Error: " + e.getMessage()); + } + } + + @Override + public Object clone () throws CloneNotSupportedException { + DemoObject t = new DemoObject(); // id = 12344 +// DemoObject t = (DemoObject) super.clone(); + t.id = id + 1; // id = 12345 + if ( t.id > 1000000) { + throw new CloneNotSupportedException ("Id overflow"); + } + return t; + } +} \ No newline at end of file diff --git a/java/samples/java-packages/source/DemoRuntime.java b/java/samples/java-packages/source/DemoRuntime.java new file mode 100644 index 0000000..94533ca --- /dev/null +++ b/java/samples/java-packages/source/DemoRuntime.java @@ -0,0 +1,41 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package lang; + +import java.io.IOException; +import java.util.concurrent.TimeUnit; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * + * @author (C)Y.D.Zakovryashin, 14.11.2022 + */ +public class DemoRuntime { + + private String cmd = "calc.exe"; + + public static void main(String[] args) { + new DemoRuntime().run(); + } + + public void run() { + Runtime r = Runtime.getRuntime(); + try { + Process p = r.exec(cmd); + p.waitFor(5, TimeUnit.SECONDS); + if (p.isAlive()) { + System.out.println("Process is alive"); + p.destroyForcibly(); + } else { + System.out.println("Process is done"); + } + System.out.println("Exit code: " + p.exitValue()); + } catch (IOException | InterruptedException ex) { + System.out.println("Error: " + ex.getMessage()); + } + } +} diff --git a/java/samples/java-packages/source/DemoString.java b/java/samples/java-packages/source/DemoString.java new file mode 100644 index 0000000..61e8123 --- /dev/null +++ b/java/samples/java-packages/source/DemoString.java @@ -0,0 +1,27 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package lang; + +/** + * + * @author (C)Y.D.Zakovryashin, 14.11.2022 + */ +public class DemoString { + + public static void main(String[] args) { + String s = "askjfsj akfkdjfal askdfjlasj asldkjflasj 1234"; +// String[] as = s.split("\\s+"); +// for (String t: as) { +// System.out.println(t); +// } + System.out.println(s.replaceAll("\\p{Digit}", "*")); + String n = "2202 2202 2222 2222"; + String t = n.substring(5, 14); + String x = "**** ****"; + n = n.replace(t, x); + System.out.println(n); + } +} diff --git a/java/samples/java-packages/source/DemoWindowAdapter.java b/java/samples/java-packages/source/DemoWindowAdapter.java new file mode 100644 index 0000000..2087476 --- /dev/null +++ b/java/samples/java-packages/source/DemoWindowAdapter.java @@ -0,0 +1,22 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package gui; + +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; + +/** + * + * @author (C)Y.D.Zakovryashin, 28.11.2022 + */ +public class DemoWindowAdapter extends WindowAdapter { + + @Override + public void windowClosing(WindowEvent e) { + System.out.println("Window closing"); + e.getWindow().dispose(); + } +} diff --git a/java/samples/java-packages/source/DemoWindowListener.java b/java/samples/java-packages/source/DemoWindowListener.java new file mode 100644 index 0000000..56b5f80 --- /dev/null +++ b/java/samples/java-packages/source/DemoWindowListener.java @@ -0,0 +1,53 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package gui; + +import java.awt.event.WindowEvent; +import java.awt.event.WindowListener; + +/** + * + * @author (C)Y.D.Zakovryashin, 28.11.2022 + */ +public class DemoWindowListener implements WindowListener { + + @Override + public void windowOpened(WindowEvent e) { + System.out.println("Window opened"); + } + + @Override + public void windowClosing(WindowEvent e) { + System.out.println("Window closing"); + e.getWindow().dispose(); + } + + @Override + public void windowClosed(WindowEvent e) { + System.out.println("Window closed"); + } + + @Override + public void windowIconified(WindowEvent e) { + System.out.println("Window iconified"); + } + + @Override + public void windowDeiconified(WindowEvent e) { + System.out.println("Window deiconified"); + } + + @Override + public void windowActivated(WindowEvent e) { + System.out.println("Window activated"); + } + + @Override + public void windowDeactivated(WindowEvent e) { + System.out.println("Window deactivated"); + } + +} diff --git a/java/samples/java-packages/source/EmptyStackException.java b/java/samples/java-packages/source/EmptyStackException.java new file mode 100644 index 0000000..8eaac2b --- /dev/null +++ b/java/samples/java-packages/source/EmptyStackException.java @@ -0,0 +1,15 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ + +package lang; + +/** + * + * @author (C)Y.D.Zakovryashin, 07.11.2022 + */ +class EmptyStackException extends Exception { + +} diff --git a/java/samples/java-packages/source/FullStackException.java b/java/samples/java-packages/source/FullStackException.java new file mode 100644 index 0000000..fff8108 --- /dev/null +++ b/java/samples/java-packages/source/FullStackException.java @@ -0,0 +1,15 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ + +package lang; + +/** + * + * @author (C)Y.D.Zakovryashin, 07.11.2022 + */ +class FullStackException extends Exception { + +} diff --git a/java/samples/java-packages/source/Stack.java b/java/samples/java-packages/source/Stack.java new file mode 100644 index 0000000..ae50a4e --- /dev/null +++ b/java/samples/java-packages/source/Stack.java @@ -0,0 +1,38 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package lang; + +/** + * + * @author (C)Y.D.Zakovryashin, 07.11.2022 + */ +public class Stack { + + public final int DEFAULT_SIZE = 128; + private T[] stack; + private int top; + + public Stack(T[] stack) { +// size = size < 1 ? DEFAULT_SIZE : size; + this.stack = stack; + top = 0; + } + + public void push(T x) throws FullStackException { + if (top == DEFAULT_SIZE) { + throw new FullStackException(); + } + stack[top] = x; + ++top; + } + + public T pop() throws EmptyStackException { + if (top < 1) { + throw new EmptyStackException(); + } + return stack[--top]; + } +} diff --git a/java/samples/multithread/ping-pong/Ball.java b/java/samples/multithread/ping-pong/Ball.java new file mode 100644 index 0000000..a231038 --- /dev/null +++ b/java/samples/multithread/ping-pong/Ball.java @@ -0,0 +1,27 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package mt; + +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * + * @author (C)Y.D.Zakovryashin, 09.01.2023 + */ +public class Ball { + + public synchronized void hit(String name, int delay) { + System.out.print(name + " -> "); + try { + notify(); + wait(); + Thread.currentThread().sleep(delay); + } catch (InterruptedException ex) { + System.out.println("Exception: " + ex.getMessage()); + } + } +} diff --git a/java/samples/multithread/ping-pong/DEV-J130.1.Введение.pdf b/java/samples/multithread/ping-pong/DEV-J130.1.Введение.pdf new file mode 100644 index 0000000..5cbcbf4 Binary files /dev/null and b/java/samples/multithread/ping-pong/DEV-J130.1.Введение.pdf differ diff --git a/java/samples/multithread/ping-pong/DEV-J130.2.Основы SQL.pdf b/java/samples/multithread/ping-pong/DEV-J130.2.Основы SQL.pdf new file mode 100644 index 0000000..303b525 Binary files /dev/null and b/java/samples/multithread/ping-pong/DEV-J130.2.Основы SQL.pdf differ diff --git a/java/samples/multithread/ping-pong/DEV-J130.4.Многопоточность.pdf b/java/samples/multithread/ping-pong/DEV-J130.4.Многопоточность.pdf new file mode 100644 index 0000000..e35a22a Binary files /dev/null and b/java/samples/multithread/ping-pong/DEV-J130.4.Многопоточность.pdf differ diff --git a/java/samples/multithread/ping-pong/DEV-J130.5.Сетевое взаимодействие.pdf b/java/samples/multithread/ping-pong/DEV-J130.5.Сетевое взаимодействие.pdf new file mode 100644 index 0000000..e077197 Binary files /dev/null and b/java/samples/multithread/ping-pong/DEV-J130.5.Сетевое взаимодействие.pdf differ diff --git a/java/samples/multithread/ping-pong/DemoThread.java b/java/samples/multithread/ping-pong/DemoThread.java new file mode 100644 index 0000000..eaabfbd --- /dev/null +++ b/java/samples/multithread/ping-pong/DemoThread.java @@ -0,0 +1,31 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package mt; + +/** + * + * @author (C)Y.D.Zakovryashin, 09.01.2023 + */ +public class DemoThread { + + public static void main(String[] args) { + SimpleThread t1 = new SimpleThread('*', 10); + SimpleThread t2 = new SimpleThread('a', 10); + SimpleThread t3 = new SimpleThread('$', 10); + Thread mt = new Thread(t1, "First"); + Thread m1 = new Thread(t2, "Second"); + Thread m2 = new Thread(t3, "Third"); + m2.setPriority(2); + mt.setPriority(7); + + mt.start(); + m1.start(); + m2.start(); + + System.out.println(m2.getId() + "." + m2.getName() + ", " + + m2.getPriority()); + } +} diff --git a/java/samples/multithread/ping-pong/PingPong.java b/java/samples/multithread/ping-pong/PingPong.java new file mode 100644 index 0000000..7ae799b --- /dev/null +++ b/java/samples/multithread/ping-pong/PingPong.java @@ -0,0 +1,54 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package mt; + +/** + * + * @author (C)Y.D.Zakovryashin, 09.01.2023 + */ +public class PingPong implements Runnable { + + public static final int ROUND = 10; + private String name; + private int delay; + private Ball ball; + + public PingPong(String name, int delay, Ball ball) { + this.name = name; + this.delay = delay; + this.ball = ball; + } + + public static void main(String[] args) throws InterruptedException { + Ball ball = new Ball(); + PingPong gamer1 = new PingPong("ping", 300, ball); + PingPong gamer2 = new PingPong("pong", 500, ball); + + Thread t1 = new Thread(gamer1); + Thread t2 = new Thread(gamer2); + + System.out.println("Start game..."); + t1.start(); + t2.start(); + try { + t1.join(8000); + t2.join(8000); + synchronized (ball) { + ball.notifyAll(); + } + } catch (InterruptedException e) { + System.out.println("Error: " + e.getMessage()); + } + System.out.println("End over."); + } + + @Override + public void run() { + for (int i = 0; i < ROUND; ++i) { + ball.hit(name, delay); + } + } +} diff --git a/java/samples/multithread/ping-pong/SimpleThread.java b/java/samples/multithread/ping-pong/SimpleThread.java new file mode 100644 index 0000000..46e923d --- /dev/null +++ b/java/samples/multithread/ping-pong/SimpleThread.java @@ -0,0 +1,40 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package mt; + +/** + * + * @author (C)Y.D.Zakovryashin, 09.01.2023 + */ +public class SimpleThread implements Runnable { + + private char c; + private int num; + + public SimpleThread(char c, int num) { + this.c = c; + this.num = num; + } + + @Override + public void run() { + for (int i = 0; i < num; ++i) { + System.out.print("-" + c); +// try { +// Thread.currentThread().sleep(500); +// } catch (InterruptedException e) { +// System.out.println("Thread \"" +// + Thread.currentThread().getName() +// + "\" is interrupted"); +// } + } + System.out.println(); + } + + public Thread getThread () { + return Thread.currentThread(); + } +} diff --git a/java/samples/multithread/ping-pong/UDPClient.java b/java/samples/multithread/ping-pong/UDPClient.java new file mode 100644 index 0000000..4647410 --- /dev/null +++ b/java/samples/multithread/ping-pong/UDPClient.java @@ -0,0 +1,158 @@ +/* + * Демонстрационное приложение. + */ +package udp; + +import java.io.BufferedReader; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.DatagramPacket; +import java.net.DatagramSocket; +import java.net.InetAddress; +import java.net.SocketException; +import java.nio.ByteBuffer; + +/** + * Класс клиента. Реализует запрос и получение файла от сервера. + * + * @author (C)Y.D.Zakovryashin, 16.01.2023 + */ +public class UDPClient { + + private DatagramSocket socket; + private DatagramPacket packet; + private byte[] buffer; + private String fileName; + + public static void main(String[] args) { + System.out.println("Client started..."); + try (DatagramSocket s = new DatagramSocket()) { + UDPClient client = new UDPClient(); + client.socket = s; + /** + * Запрос у пользователя имени файла для загрузки. + */ + client.getFileName(); + /** + * Запрос файла с сервера. + */ + client.sendFileName(); + /** + * Чтение ответа сервера, содержащего либо размер файла, либо код + * ERROR, который означает отсутствие запрошенного файла на сервере. + */ + long size = client.getFileSize(); + if (size > UDPServer.ERROR) { + try { + /** + * Загрузка файла с сервера. + */ + client.getFile(size); + System.out.println("File \"" + client.fileName + + "\" is downloaded successfully."); + } catch (IOException e) { + /** + * Произошла ошибка чтения файла. + */ + System.err.println("File \"" + client.fileName + + "\" isn\'t downloaded.\n" + e.getMessage()); + } + } else { + /** + * Сервер вернул код ERROR, который означает, что на сервере нет + * файла с запрошенным именем. + */ + System.out.println("File \"" + client.fileName + "\" not found"); + } + } catch (SocketException ex) { + System.out.println("Error #1: " + ex.getMessage()); + } catch (IOException ex) { + System.out.println("Error #2: " + ex.getMessage()); + } + System.out.println("Client stoped."); + } + + /** + * Чтение имени запрашиваемого файла с консоли. + * + * @return строку с именем файла. + */ + private void getFileName() { + try (BufferedReader in = new BufferedReader( + new InputStreamReader(System.in));) { + /** + * Цикл запроса имени файла должен выполняться до тех пор, пока + * пользователь не введёт непустое имя файла. + */ + do { + System.out.println(">>> Input file name for download:"); + fileName = in.readLine(); + } while (fileName == null || fileName.trim().isEmpty()); + } catch (IOException e) { + System.out.println("Errror: " + e.getMessage()); + } + System.out.println("Step 1"); + } + + /** + * Отправка запроса с именем файла. + * + * @param fileName строка с именем файла. + * @throws IOException в случае общей ошибки ввода/вывода. + */ + private void sendFileName() throws IOException { + buffer = fileName.getBytes(); + /** + * В пакет заносится адрес сервера, его порт и сериализованное имя + * файла. + */ + packet = new DatagramPacket(buffer, buffer.length, + InetAddress.getByName(UDPServer.UDP_SERVER_ADDRESS), + UDPServer.UDP_SERVER_PORT); + socket.send(packet); + System.out.println("Step 2"); + } + + /** + * Получение первого пакета от сервера с размером файла и отправка пакета с + * подтверждением о готовности принять файл. + * + * @return размер файла. + * @throws IOException в случае общей ошибки ввода/вывода. + */ + private long getFileSize() throws IOException { + buffer = new byte[8]; + packet = new DatagramPacket(buffer, buffer.length); + /** + * Получение пакета с размером файла. + */ + socket.receive(packet); + long size = ByteBuffer.wrap(packet.getData()).getLong(); + if (size > UDPServer.ERROR && size < Integer.MAX_VALUE) { + buffer = UDPServer.OK.getBytes(); + } else { + buffer = UDPServer.NO.getBytes(); + } + /** + * Подготовка и отправка пакета с подтверждением о готовности принять + * файл. + */ + packet.setData(buffer); + packet.setLength(buffer.length); + socket.send(packet); + System.out.println("Step 3"); + return size; + } + + private void getFile(long size) throws IOException { + int s = size > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) size; + buffer = new byte[s]; + packet.setData(buffer); + socket.receive(packet); + try (FileOutputStream fos = new FileOutputStream("Copy-" + fileName)) { + fos.write(buffer); + } + System.out.println("Step 4"); + } +} diff --git a/java/samples/multithread/ping-pong/UDPServer.java b/java/samples/multithread/ping-pong/UDPServer.java new file mode 100644 index 0000000..21b9563 --- /dev/null +++ b/java/samples/multithread/ping-pong/UDPServer.java @@ -0,0 +1,120 @@ +/* + * Демонстрационное приложение. Сервер приложения. + */ +package udp; + +import java.io.BufferedReader; +import java.io.DataOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.DatagramPacket; +import java.net.DatagramSocket; +import java.net.InetAddress; +import java.net.SocketException; +import java.nio.ByteBuffer; + +/** + * Класс сервера. Обеспечивает отправку клиенту запрошенного файла. + * + * @author (C)Y.D.Zakovryashin, 16.01.2023 + */ +public class UDPServer { + + public static final int UDP_SERVER_PORT = 12345; + public static final String UDP_SERVER_ADDRESS = "localhost"; + public static final String OK = "Ok"; + public static final String NO = "No"; + public static final int ERROR = -1; + public static final int BUFFER_SIZE = 255; + private DatagramSocket socket; + private DatagramPacket packet; + private byte[] buffer; + private String fileName; + private long fileLength; + private boolean exists; + + public static void main(String[] args) { + System.out.println("Server started..."); + try (DatagramSocket s = new DatagramSocket(UDP_SERVER_PORT)) { + UDPServer server = new UDPServer(); + server.socket = s; + /** + * Ожидание запроса клиента с именем файла. + */ + server.getFileName(); + /** + * Отправка клиенту результата поиска файла: либо размера найденного + * файла, либо кода ERROR, который означает отсутствие запрошенного + * файла на сервере. + */ + server.sendResult(); + /** + * Отправка файла с сервера. + */ + if (server.exists && server.getClientReply()) { + server.sendFile(); + System.out.println("Server: File \"" + server.fileName + + "\" is sent successfully."); + } + } catch (SocketException ex) { + System.out.println("Server error #1: " + ex.getMessage()); + } catch (IOException e) { + /** + * Произошла ошибка ввода/вывода файла. + */ + System.err.println("Server error #2: " + e.getMessage()); + } + System.out.println("Server stoped."); + } + + /** + * Чтение имени запрашиваемого файла с консоли. + * + * @return строку с именем файла. + */ + private void getFileName() throws IOException { + buffer = new byte[BUFFER_SIZE]; + packet = new DatagramPacket(buffer, BUFFER_SIZE); + socket.receive(packet); + fileName = new String(packet.getData(), 0, packet.getLength()); + System.out.println("Step 1: file name: " + fileName); + } + + private void sendResult() throws IOException { + File f = new File(fileName); + buffer = new byte[8]; + if (exists = f.exists()) { + fileLength = f.length(); + ByteBuffer.wrap(buffer).putLong(fileLength); + } else { + ByteBuffer.wrap(buffer).putLong(ERROR); + } + packet.setData(buffer); + packet.setLength(8); + socket.send(packet); + System.out.println("Step 2"); + } + + private boolean getClientReply() throws IOException { + buffer = new byte[4]; + packet.setData(buffer); + socket.receive(packet); + String r = new String(packet.getData()).trim(); + System.out.println("Step 3"); + return r.equals("Ok"); + } + + private void sendFile() throws IOException { + buffer = new byte[(int) fileLength]; + try (FileInputStream fis = new FileInputStream(fileName)) { + int s = fis.read(buffer); + } + packet.setData(buffer); + socket.send(packet); + System.out.println("Step 4"); + } + +}