فهرست سرفصل‌های Java
خونه (HOME) مقدمه (Intro) شروع کار (Get Started) نحوه نگارش (Syntax) دستورات (Statements) خروجی (Output) چاپ اعداد (Print Numbers) کامنت ها (Comments) متغیرها (Variables) چاپ متغیرها (Print Variables) چندین متغیر (Multiple Variables) شناسه ها (Identifiers) ثابت ها / فاینال (Constants (Final)) نمونه های واقعی (Real-Life Examples) انواع داده (Data Types) اعداد (Numbers) بولی ها (Booleans) کاراکترها (Characters) نمونه واقعی (Real-Life Example) غیراولیّه ها (Non-primitive Types) کلیدواژه var (The var Keyword) تبدیل نوع (Type Casting) حسابی (Arithmetic) انتساب (Assignment) مقایسه (Comparison) منطقی (Logical) اولویت (Precedence) رشته ها (Strings) به هم چسباندن (Concatenation) اعداد و رشته ها (Numbers and Strings) کاراکترهای ویژه (Special Characters) بولی ها (Booleans) شرط ها If...Else (If...Else) else else if حالت کوتاه if...else (Short Hand If...Else) عملگرهای منطقی (Logical Operators) نمونه های واقعی (Real-Life Examples) سوییچ (Switch) حلقه while (While Loop) نمونه های واقعی while (Real-Life Examples) حلقه for (For Loop) حلقه های تو در تو (Nested Loops) حلقه foreach (For-Each Loop) نمونه های واقعی for (Real-Life Examples) شکستن/ادامه (Break/Continue) آرایه ها (Arrays) حلقه روی آرایه (Loop Through an Array) نمونه های واقعی آرایه (Real-Life Examples) آرایه های چندبعدی (Multidimensional Arrays) متدها (Methods) پارامترهای متد (Method Parameters) مقادیر بازگشتی (Return Values) سربارگذاری متد (Method Overloading) اسکوپ (Scope) بازگشتی (Recursion) شی ءگرایی (OOP) کلاس ها/اشیاء (Classes/Objects) خصوصیات کلاس (Class Attributes) متدهای کلاس (Class Methods) سازنده ها (Constructors) this (this Keyword) تعدیل کننده ها (Modifiers) تعدیل کننده های دسترسی (Access Modifiers) تعدیل کننده های غیردسترسی (Non-Access Modifiers) کپسوله سازی (Encapsulation) پکیج ها / API (Packages / API) ارث بری (Inheritance) چندریختی (Polymorphism) super (super Keyword) کلاس های درونی (Inner Classes) انتزاع (Abstraction) اینترفیس (Interface) ناشناس (Anonymous) enumها (Enum) سازنده در enum (Enum Constructor) ورودی کاربر (User Input) تاریخ (Date) خطاها (Errors) دیباگ (Debugging) استثناها (Exceptions) چند استثنا (Multiple Exceptions) try-with-resources کار با فایل (Files) ایجاد فایل (Create Files) نوشتن فایل (Write Files) خواندن فایل (Read Files) حذف فایل (Delete Files) جریان های I/O (I/O Streams) FileInputStream FileOutputStream BufferedReader BufferedWriter ساختار داده (Data Structures) کالکشن ها (Collections) لیست (List) آرِیلیست (ArrayList) لینکدلیست (LinkedList) مرتب سازی لیست (List Sorting) مجموعه (Set) هش ست (HashSet) تری ست (TreeSet) لینکدهش ست (LinkedHashSet) نقشه (Map) هش مپ (HashMap) تری مپ (TreeMap) لینکدهش مپ (LinkedHashMap) ایتراتور (Iterator) الگوریتم ها (Algorithms) کلاس های بسته بندی (Wrapper Classes) جنریک ها (Generics) انوتیشن ها (Annotations) عبارات باقاعده (RegEx) رشته ها (Threads) لامبدا (Lambda) مرتب سازی پیشرفته (Advanced Sorting) پروژه ها (Projects) چگونه ها (How Tos) جمع دو عدد (Add Two Numbers) جابجایی دو متغیر (Swap Two Variables) زوج یا فرد (Even or Odd Number) برعکس کردن عدد (Reverse a Number) مثبت یا منفی (Positive or Negative) ریشه مربع (Square Root) مساحت مستطیل (Area of Rectangle) درجه سلسیوس به فارنهایت (Celsius to Fahrenheit) جمع ارقام (Sum of Digits) عدد آرمسترانگ (Check Armstrong Num) عدد تصادفی (Random Number) شمارش کلمات (Count Words) شمارش حروف صدادار (Count Vowels in a String) حذف حروف صدادار (Remove Vowels) شمارش ارقام در رشته (Count Digits in a String) برعکس کردن رشته (Reverse a String) بررسی پالیندروم (Palindrome Check) بررسی اَناگرام (Check Anagram) تبدیل رشته به آرایه (Convert String to Array) حذف فاصله های خالی (Remove Whitespace) شمارش فراوانی کاراکتر (Count Character Frequency) جمع عناصر آرایه (Sum of Array Elements) میانگین آرایه (Find Array Average) مرتب سازی آرایه (Sort an Array) کوچک ترین عنصر (Find Smallest Element) بزرگ ترین عنصر (Find Largest Element) ادغام دو آرایه (Merge Two Arrays) حذف تکراری ها (Remove Duplicates) پیدا کردن مقادیر تکراری (Find Duplicates) درهم زدن آرایه (Shuffle an Array) فاکتوریل (Factorial of a Number) دنباله فیبوناچی (Fibonacci Sequence) ب.م.م (Find GCD) تشخیص اول بودن (Check Prime Number) حلقه روی ArrayList (ArrayList Loop) حلقه روی HashMap (HashMap Loop) حلقه روی Enum (Loop Through an Enum) مرجع جاوا (Reference) کلیدواژه ها (Keywords) assert abstract boolean break byte case catch char class continue default do double else enum exports extends final finally float for if implements import instanceof int interface long module native new package private protected public return requires short static super switch synchronized this throw throws transient try var void volatile while متدهای رشته (String Methods) charAt() codePointAt() codePointBefore() codePointCount() compareTo() compareToIgnoreCase() concat() concat() contentEquals() contentEquals() endsWith() equals() equalsIgnoreCase() format() getBytes() getChars() hashCode() indexOf() isEmpty() join() lastIndexOf() length() matches() matches() regionMatches() replace() replaceAll() replaceFirst() split() subSequence() substring() toCharArray() toLowerCase() toString() toUpperCase() trim() valueOf() متدهای ریاضی (Math Methods) abs() acos() addExact() atan2() cbrt() ceil() copySign() cos() cosh() exp() expm1() getExponent() hypot() incrementExact() log() log10() log1p() max() min() multiplyExact() negateExact() nextAfter() nextDown() nextUp() pow() random() rint() round() scalb() signum() sin() sinh() sqrt() subtractExact() tan() tanh() toDegrees() toIntExact() toRadians() ulp() روش های خروجی (Java Output Methods) print() printf() println() روش های آرایه ها (Java Arrays Methods) compare() equals() sort() fill() length روش های ArrayList (Java ArrayList Methods) add() addAll() clear() clone() contains contains contains contains contains contains iterator() lastIndexOf() listIterator() remove() removeAll() removeIf() replaceAll() retainAll() retainAll() set() size() sort() spliterator() toArray() trimToSize() trimToSize() روش های LinkedList (Java LinkedList Methods) add() add() addAll() clear() clone() contains forEach() get() getFirst() getLast() indexOf() isEmpty() iterator() lastIndexOf() lastIndexOf() listIterator() remove()
Java

Java — رشته ها (Threads)

آخرین بروزرسانی: 1404/08/05

رشته ها (Threads)

«رشته ها (Threads)» یعنی اجرای چند کار هم زمان. این کار، کارایی را بالا می برد. همچنین، کارهای سنگین در پس زمینه اجرا می شوند و برنامه اصلی قطع نمی شود.

ایجاد و اجرای رشته با ارث بری از Thread

در این روش از کلاس Thread ارث می بری و متد run() را بازنویسی می کنی. سپس با start() اجرا می کنی.

public class Main extends Thread {
  public static void main(String[] args) {
    Main thread = new Main();
    thread.start();
    System.out.println("This code is outside of the thread");
  }
  public void run() {
    System.out.println("This code is running in a thread");
  }
}

مشاهده در ادیتور

گام های تمرینی

  1. یک حلقه در run() بگذار و اعداد چاپ کن.
  2. بعد از start()، پیامی در main چاپ کن.
  3. خروجی نامنظم را مشاهده کن.

ایجاد و اجرای رشته با پیاده سازی Runnable

در این روش، Runnable را پیاده سازی می کنی. سپس شیء Runnable را به سازنده Thread می دهی و start() را صدا می زنی.

public class Main implements Runnable {
  public static void main(String[] args) {
    Main obj = new Main();
    Thread thread = new Thread(obj);
    thread.start();
    System.out.println("This code is outside of the thread");
  }
  public void run() {
    System.out.println("This code is running in a thread");
  }
}

مشاهده در ادیتور

نکته: با ارث بری از Thread، دیگر از کلاس دیگری ارث نمی بری. اما با Runnable می توانی از کلاس دیگری هم ارث ببری.

مشکلات هم زمانی (Concurrency)

ترتیب اجرا معلوم نیست. وقتی چند رشته یک متغیر مشترک را تغییر می دهند، مقدار نهایی غیرقابل پیش بینی می شود.

public class Main extends Thread {
  public static int amount = 0;
  public static void main(String[] args) {
    Main thread = new Main();
    thread.start();
    System.out.println(amount);
    amount++;
    System.out.println(amount);
  }
  public void run() {
    amount++;
  }
}

مشاهده در ادیتور

کاهش ریسک هم زمانی با isAlive()

می توانی صبر کنی تا رشته تمام شود. سپس روی داده مشترک کار کنی. این کار، نتیجه را پایدارتر می کند.

public class Main extends Thread {
  public static int amount = 0;
  public static void main(String[] args) {
    Main thread = new Main();
    thread.start();
    while (thread.isAlive()) {
      System.out.println("Waiting...");
    }
    System.out.println("Main: " + amount);
    amount++;
    System.out.println("Main: " + amount);
  }
  public void run() {
    amount++;
  }
}

مشاهده در ادیتور

برای ادامه مسیر، بخش عبارات باقاعده را مرور کن. سپس به عبارت های لامبدا برو.

جمع بندی سریع

  • Thread کارها را هم زمان اجرا می کند.
  • start()، اجرای run() را آغاز می کند.
  • Runnable انعطافِ ارث بری بهتر می دهد.
  • هم زمانی، مقدارها را نامطمئن می کند.
  • isAlive() به هماهنگی ساده کمک می کند.