1. Inherit the Thread class
public class MyThread extends Thread {
@Override
public void run(a) {
System.out.println("MyThread run"); }}public class Test {
public static void main(String[] args) {
MyThread myThread = newMyThread(); myThread.start(); }}Copy the code
2. Implement the Runnable interface
public class MyRunnable implements Runnable {
@Override
public void run(a) {
System.out.println("MyRunnable run"); }}public class Test {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = newThread(myRunnable); thread.start(); }}Copy the code
3. The currentThread () method
The currentThread() method returns information about which thread the code snippet is being called by
public class MyThread extends Thread {
public MyThread(a) {
System.out.println("Constructor print:" + Thread.currentThread().getName());
}
@Override
public void run(a) {
System.out.println("The run method prints:"+ Thread.currentThread().getName()); }}public class Test {
public static void main(String[] args) {
MyThread myThread = newMyThread(); myThread.start(); }}Copy the code
4. The isAlive () method
The isAlive() method determines whether the current thread is active
public class MyThread extends Thread {
@Override
public void run(a) {
System.out.println("run isAlive= " + this.isAlive()); }}public class Test {
public static void main(String[] args) throws InterruptedException {
MyThread myThread = new MyThread();
System.out.println("before isAlive=" + myThread.isAlive());
myThread.start();
// Thread.sleep(1000);
System.out.println("after isAlive="+ myThread.isAlive()); }}Copy the code
5. The sleep () method
The sleep() method puts the current “executing thread” to sleep(suspends execution) for the specified number of milliseconds. “Executing thread” refers to the thread returned by this.currentThread()
public class MyThread extends Thread {
@Override
public void run(a) {
try {
System.out.println("run begin threadName=" + this.getName() + " time=" + System.currentTimeMillis());
Thread.sleep(2000);
System.out.println("run end threadName=" + this.getName() + " time=" + System.currentTimeMillis());
} catch(InterruptedException e) { e.printStackTrace(); }}}public class Test {
public static void main(String[] args) throws InterruptedException {
MyThread myThread = new MyThread();
System.out.println("begin time=" + System.currentTimeMillis());
myThread.start();
System.out.println("end time="+ System.currentTimeMillis()); }}Copy the code
6. GetId () method
The getId() method gets the unique identity of the thread
public class Test {
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName() + ""+ Thread.currentThread().getId()); }}Copy the code
7. Stop the thread
7.1 interrupt () method
The interrupt() method does not interrupt the thread immediately. It merely marks the thread with an interrupt, not an actual interrupt
public class MyThread extends Thread {
@Override
public void run(a) {
for (int i = 0; i <500000; i++) { System.out.println("i="+ i); }}}public class Test {
public static void main(String[] args) throws InterruptedException {
MyThread myThread = new MyThread();
myThread.start();
Thread.sleep(500); myThread.interrupt(); }}Copy the code
7.2 Checking whether the Thread is interrupted
-
The interrupted() method checks whether the current thread is interrupted and clears the interrupted state if it is
public class Test { public static void main(String[] args) { Thread.currentThread().interrupt(); System.out.println("Do I stop 1?" + Thread.interrupted()); System.out.println("Do I stop 2?" + Thread.interrupted()); System.out.println("end"); }}Copy the code
-
The isInterrupted() method checks whether the thread isInterrupted and does not clear the interrupted status
public class MyThread extends Thread { @Override public void run(a) { for (int i = 0; i <500000; i++) { System.out.println("i="+ i); }}}public class Test { public static void main(String[] args) throws InterruptedException { MyThread myThread = new MyThread(); myThread.start(); Thread.sleep(500); myThread.interrupt(); System.out.println("Do I stop 1?" + myThread.isInterrupted()); System.out.println("Do I stop 2?" + myThread.isInterrupted()); System.out.println("end"); }}Copy the code
7.3 Stopping threads using Exceptions (Recommended)
public class MyThread extends Thread {
@Override
public void run(a) {
try {
for (int i = 0; i <500000; i++) {if (this.isInterrupted()) {
System.out.println("Interrupted state, exit");
throw new InterruptedException();
}
System.out.println("i=" + i);
}
System.out.println("Below the for loop");
} catch (InterruptedException e) {
System.out.println("MyThread catch"); e.printStackTrace(); }}}public class Test {
public static void main(String[] args) {
try {
MyThread myThread = new MyThread();
myThread.start();
Thread.sleep(500);
myThread.interrupt();
} catch (InterruptedException e) {
System.out.println("main catch");
e.printStackTrace();
}
System.out.println("main end"); }}Copy the code
7.4 Stop thread-sleep method
-
Sleep and then interrupt
public class MyThread extends Thread { @Override public void run(a) { try { System.out.println("run begin"); Thread.sleep(20000); System.out.println("run end"); } catch (InterruptedException e) { System.out.println("MyThread catch isInterrupted=" + this.isInterrupted()); e.printStackTrace(); }}}public class Test { public static void main(String[] args) throws InterruptedException { MyThread myThread = new MyThread(); myThread.start(); Thread.sleep(2000); myThread.interrupt(); }}Copy the code
-
Interrupt first and then hibernate
public class MyThread extends Thread { @Override public void run(a) { try { System.out.println("run begin"); for (int i = 0; i <500000; i++) { System.out.println("i=" + i); if (i == 400000) { Thread.sleep(100); } } System.out.println("run end"); } catch (InterruptedException e) { System.out.println("MyThread catch"); e.printStackTrace(); }}}public class Test { public static void main(String[] args) throws InterruptedException { MyThread myThread = newMyThread(); myThread.start(); myThread.interrupt(); }}Copy the code
7.5 Stopping threads – Violence method (Not recommended)
-
The stop() method can stop threads by force
public class MyThread extends Thread { @Override public void run(a) { try { int i = 0; while (true) { System.out.println("i=" + (i++)); Thread.sleep(100); }}catch(InterruptedException e) { e.printStackTrace(); }}}public class Test { public static void main(String[] args) throws InterruptedException { MyThread myThread = new MyThread(); myThread.start(); Thread.sleep(2000); myThread.stop(); }}Copy the code
-
The stop() method has been deprecated. Forcing a thread to stop may cause some rational work not to be completed. In addition, the lock object may be unlocked. As a result, data cannot be synchronized and data inconsistency occurs
public class Service { private String username = "a"; private String password = "aaa"; public String getUsername(a) { return username; } public String getPassword(a) { return password; } synchronized public void login(String username, String password) { try { this.username = username; Thread.sleep(20000); this.password = password; } catch(InterruptedException e) { e.printStackTrace(); }}}public class MyThread extends Thread { private Service service; public MyThread(Service service) { this.service = service; } @Override public void run(a) { service.login("b"."bbb"); }}public class Test { public static void main(String[] args) throws InterruptedException { Service service = new Service(); MyThread myThread = new MyThread(service); myThread.start(); Thread.sleep(2000); myThread.stop(); System.out.println("username=" + service.getUsername() + " password="+ service.getPassword()); }}Copy the code
7.6 Stopping a Thread – Return method
public class MyThread extends Thread {
@Override
public void run(a) {
int i = 0;
while (true) {
if (this.isInterrupted()) {
System.out.println("Stop, quit.");
return;
}
System.out.println("i="+ (i++)); }}}public class Test {
public static void main(String[] args) throws InterruptedException {
MyThread myThread = new MyThread();
myThread.start();
Thread.sleep(3000); myThread.interrupt(); }}Copy the code
8. Suspending threads (not recommended)
8.1 Use of methods suspend() and resume()
public class MyThread extends Thread {
private long i;
public long getI(a) {
return i;
}
@Override
public void run(a) {
while (true) { i++; }}}public class Test {
public static void main(String[] args) throws InterruptedException {
MyThread myThread = new MyThread();
myThread.start();
Thread.sleep(3000);
myThread.suspend();
System.out.println("suspend 1-1 time=" + System.currentTimeMillis() + " i=" + myThread.getI());
Thread.sleep(3000);
System.out.println("suspend 1-2 time=" + System.currentTimeMillis() + " i=" + myThread.getI());
myThread.resume();
Thread.sleep(3000);
myThread.suspend();
System.out.println("suspend 2-1 time=" + System.currentTimeMillis() + " i=" + myThread.getI());
Thread.sleep(3000);
System.out.println("suspend 2-2 time=" + System.currentTimeMillis() + " i="+ myThread.getI()); }}Copy the code
8.2 Disadvantages of suspend() and resume() methods – exclusivity
-
Case1:
public class Service { synchronized public void testA(a) { System.out.println(Thread.currentThread().getName() + " begin"); if (Thread.currentThread().getName().equals("a")) { System.out.println(Thread.currentThread().getName() + " suspend"); Thread.currentThread().suspend(); } System.out.println(Thread.currentThread().getName() + " end"); }}public class Test { public static void main(String[] args) throws InterruptedException { final Service service = new Service(); Thread a = new Thread() { @Override public void run(a) { service.testA(); }}; a.setName("a"); a.start(); Thread.sleep(1000); Thread b = new Thread() { @Override public void run(a) { service.testA(); }}; b.setName("b"); b.start(); }}Copy the code
-
Case2: system.out.println () is a string printed by synchronized synchronized blocks. Suspend () results in failure to release the lock object held by synchronized, so “main end” cannot be printed in this case
public class MyThread extends Thread { @Override public void run(a) { int i = 0; while (true) { i++; System.out.println(i); }}}public class Test { public static void main(String[] args) throws InterruptedException { MyThread myThread = new MyThread(); myThread.start(); Thread.sleep(3000); myThread.suspend(); System.out.println("main end"); }}Copy the code
8.3 Disadvantages of the suspend() and resume() methods – out of sync
public class Service {
private String username = "a";
private String password = "aaa";
public void setValue(String username, String password) {
this.username = username;
if (Thread.currentThread().getName().equals("a")) {
System.out.println(Thread.currentThread().getName() + " suspend");
Thread.currentThread().suspend();
}
this.password = password;
}
public void getValue(a) {
System.out.println(username + ""+ password); }}public class Test {
public static void main(String[] args) throws InterruptedException {
final Service service = new Service();
Thread a = new Thread(new Runnable() {
@Override
public void run(a) {
service.setValue("b"."bbb"); }}); a.setName("a");
a.start();
Thread.sleep(2000); service.getValue(); }}Copy the code
9. The yield () method
The yield() method allows the current thread to give up CPU resources to other threads at an indeterminate time, perhaps immediately after giving up the resources
public class Test {
public static void main(String[] args) {
Thread thread = new Thread(new Runnable() {
@Override
public void run(a) {
long beginTime = System.currentTimeMillis();
int count = 0;
for (int i = 0; i <5000000; i++) {// Thread.yield();
count = count + (i + 1);
}
long endTime = System.currentTimeMillis();
System.out.println("Time:" + (endTime - beginTime) + "毫秒"); }}); thread.start(); }}Copy the code
10. Thread priority
10.1 Thread priority inheritance features
The priority of A thread is inherited. For example, if thread A starts thread B, thread A and thread B have the same priority
public class ThreadA extends Thread {
@Override
public void run(a) {
System.out.println(Thread.currentThread().getName() + " priority=" + this.getPriority());
ThreadB b = newThreadB(); b.start(); }}public class ThreadB extends Thread {
@Override
public void run(a) {
System.out.println(Thread.currentThread().getName() + " priority=" + this.getPriority()); }}public class Test {
public static void main(String[] args) {
ThreadA a = new ThreadA();
a.setPriority(8); a.start(); }}Copy the code
10.2 setPriority () method
The setPriority() method sets the priority of a thread (1-10). High-priority threads always execute mostly first, but this does not mean that high-priority threads complete first
public class ThreadA extends Thread {
@Override
public void run(a) {
for (int i = 0; i <500000; i++) { System.out.println(Thread.currentThread().getName() +"* * * * *"); }}}public class ThreadB extends Thread {
@Override
public void run(a) {
for (int i = 0; i <500000; i++) { System.out.println(Thread.currentThread().getName() +"-- -- -- -- -- -"); }}}public class Test {
public static void main(String[] args) {
ThreadA a = new ThreadA();
a.setName("ThreadA");
a.setPriority(1);
ThreadB b = new ThreadB();
b.setName("ThreadB");
b.setPriority(10); a.start(); b.start(); }}Copy the code
11. Daemon threads
There are two types of Java threads: user threads and daemon threads. When no user thread exists in the process, the daemon thread is automatically destroyed. A typical example of a daemon thread is a garbage collector thread
public class MyThread extends Thread {
@Override
public void run(a) {
try {
int i = 0;
while (true) {
System.out.println(Thread.currentThread().getName() + " i=" + (i++));
Thread.sleep(500); }}catch(InterruptedException e) { e.printStackTrace(); }}}public class Test {
public static void main(String[] args) throws InterruptedException {
MyThread myThread = new MyThread();
myThread.setDaemon(true);
myThread.start();
Thread.sleep(2000);
System.out.println("main end"); }}Copy the code
Learn from “Java Multi-threaded Programming Core Technology”