📅  最后修改于: 2023-12-03 15:16:02.694000             🧑  作者: Mango
Java.lang.Thread是Java中的一个基本类,用于实现线程。线程是一种轻量级进程,能够使程序以并行方式运行。Java.lang.Thread类提供了一种创建和操作线程的方式,让程序员能够控制线程的行为。
Java.lang.Thread类提供了两种方式来创建线程:
要创建一个线程并继承Thread类,需要重写run()方法,该方法包含要执行的代码。可以使用start()方法启动线程。下面是一个例子:
public class MyThread extends Thread {
public void run() {
System.out.println("Running");
}
}
public class Main {
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start();
}
}
要使用Runnable接口创建线程,可以将实现Runnable的类作为Thread类的构造函数参数。该类必须包含run()方法。下面是一个例子:
public class MyRunnable implements Runnable {
public void run() {
System.out.println("Running");
}
}
public class Main {
public static void main(String[] args) {
Runnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
}
}
线程在其生命周期中会经历不同的状态,Java.lang.Thread类提供了方法来获取线程的状态:
Java.lang.Thread类提供了方法来获取线程的状态:
下面是一个例子:
public class MyThread extends Thread {
public void run() {
System.out.println("Running");
}
}
public class Main {
public static void main(String[] args) {
MyThread myThread = new MyThread();
System.out.println("State:" + myThread.getState()); // NEW
myThread.start();
System.out.println("State:" + myThread.getState()); // RUNNABLE
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("State:" + myThread.getState()); // TERMINATED
System.out.println("Alive? " + myThread.isAlive()); // false
}
}
当多个线程同时访问共享资源时,就会出现竞争条件,导致数据不一致或异常。Java.lang.Thread类提供了几种同步机制来避免竞争条件:
下面是一个例子,使用synchronized来保证账户余额的安全:
public class BankAccount {
private int balance = 100;
public synchronized void withdraw(int amount) {
if(balance >= amount) {
balance -= amount;
System.out.println("Withdrawn " + amount + ", balance is " + balance);
} else {
System.out.println("Not enough balance");
}
}
}
public class MyThread extends Thread {
private BankAccount account;
public MyThread(BankAccount account) {
this.account = account;
}
public void run() {
account.withdraw(50);
}
}
public class Main {
public static void main(String[] args) {
BankAccount account = new BankAccount();
MyThread thread1 = new MyThread(account);
MyThread thread2 = new MyThread(account);
thread1.start();
thread2.start();
}
}
Java.lang.Thread类提供了方法来设置和获取线程的优先级:
线程的优先级并不一定决定了线程的执行顺序,只是给CPU调度器提供一个参考。下面是一个例子:
public class MyThread extends Thread {
public void run() {
System.out.println("Running " + Thread.currentThread().getName() + ", priority is " + Thread.currentThread().getPriority());
}
}
public class Main {
public static void main(String[] args) {
MyThread thread1 = new MyThread();
MyThread thread2 = new MyThread();
thread1.setPriority(Thread.MIN_PRIORITY);
thread2.setPriority(Thread.MAX_PRIORITY);
thread1.start();
thread2.start();
}
}
Java.lang.Thread是Java中一个重要的类,用于实现多线程编程。程序员可以使用Java.lang.Thread类提供的方法来创建线程、获取线程状态和优先级、实现线程的同步等。了解Java.lang.Thread类是Java多线程编程必不可少的知识。