Thrad类 ——线程的描述(每个线程都有一个Thread类与之一一关联)
即演变成如何创建一个Thread对象???
1>.继承Thread类,覆写run方法
2>.实现Runnable接口的类,覆写run方法
public class CreateThread {
private static class MyThread extends Thread {//继承自Thread
@Override
public void run() {
// 让该线程去做的事情
}
}
private static class MyRunnable implements Runnable {//实现的是Runnable接口
@Override
public void run() {
// 让该线程去做的事情
}
}
public static void main(String[] args) {
// 创建好了 Thread 的对象,描述
Thread thread1 = new MyThread();//创建了一个用MyThread实现的线程类
Thread thread2 = new Thread(new MyRunnable());
Thread thread3 = new Thread(new MyThread());//和thread1一样
// 启动线程,若不调用start(),则Thread只是一个对象
thread1.start();
thread2.start();
thread3.start();
// 常见的方法-继承 Thread (匿名类/lambda)
Thread thread4 = new Thread() {
@Override
public void run() {
// 覆写 run 方法的代码
}
};
// 常见的方法-继承 Runnable (匿名类/lambda)
Thread thread6 = new Thread(new Runnable() {
@Override
public void run() {
// 覆写 run 方法的代码
}
});
Thread thread7 = new Thread(() -> {
// 覆写 run 方法的代码
});
}
}
实例:
public class CreateThread1 {
private static class ShareResource {
public int n = 0;
}
private static class MyThread extends Thread {
private int n = 0;
@Override
public void run() {
while (n < 10) {
System.out.println(n);
try {
Thread.sleep(500);//0.5秒暂停一下
} catch (InterruptedException e) {
e.printStackTrace();
}
n++;
}
}
}
private static class MyThread2 extends Thread {
private ShareResource resource;
public MyThread2(ShareResource resource) {
this.resource = resource;
}
@Override
public void run() {
while (resource.n < 10) {
System.out.println(resource.n);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
resource.n++;
}
}
}
public static void main(String[] args) {
/*
Thread thread1 = new MyThread();
Thread thread2 = new MyThread();//可共享
*/
/*
Thread thread1 = new Thread(new MyThread());
Thread thread2 = new Thread(new MyThread());//不可共享
*/
/*
MyThread runnable = new MyThread();
Thread thread1 = new Thread(runnable);
Thread thread2 = new Thread(runnable);
*/
ShareResource resource = new ShareResource();
Thread thread1 = new MyThread2(resource);
Thread thread2 = new MyThread2(resource);
thread1.start();
thread2.start();
}
}