一、在Java中创建线程有两种方法:继承Thread类(继承方式)和使用Runnable接口(实现方式)。
二、在使用Runnable接口时需要建立一个Thread实例。因此,无论是通过Thread类还是Runnable接口建立线程,都必须建立Thread类或它的子类的实例。
三、对比一下继承的方式 vs 实现的方式
1、 哪个方式好? :
* 实现的方式优于继承的方式
2、 why? :
* ① 避免了java单继承的局限性
* ② 如果多个线程要操作同一份资源(或数据),更适合使用实现的方式
====================================
方法一:
//通过继承的方式
//创建多线程的方式一:继承于Thread类
class MyThread1 extends Thread {
public void run() {
System.out.println("MyThread.run()1");
}
}
public class thread1{
public static void main(String[] args) {
//创建一个类对象
MyThread1 myThread1 = new MyThread1();
//调用start()方法:启动线程并执行run()
myThread1.start();
//再创建一个线程
MyThread1 myThread2 = new MyThread1();
myThread2.start();
}
}
====================================
方法二:
//通过实现的方式
//创建多线程的方式二:创建一个实现了Runnable接口的类
class MyThread2 implements Runnable {
//实现接口的抽象方法
public void run() {
System.out.println("MyThread.run()2");
}
}
public class thread2 {
public static void main(String[] args) {
//创建一个Runnable接口实现类的对象
MyThread2 myThread = new MyThread2();
//将此对象作为形参传递给Thread类的构造器中,创建Thread类的对象,此对象即为一个线程
Thread thread = new Thread(myThread);
//调用start()方法:启动线程并执行run()
thread.start();
//再创建一个线程
Thread thread2 = new Thread(myThread);
thread2.start();
}
}
====================================
打酱油的一个方法
//创建多线程的方式三: 直接写到主线程里面
public class thread3 {
public static void main(String[] args) {
new Runnable() {
public void run() {
int i = 0;
while(i<5){
try {
i=i+1;
System.out.println("run()3:"+i);
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}.run(); //只能用run()
new Thread(){
public void run() {
int i = 0;
while(i<5){
try {
i=i+1;
System.out.println("run()4:"+i);
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}.start(); //能用run()或者start()
}
}
====================================
Thread的常用方法:
* 1.start():启动线程并执行相应的run()方法
* 2.run():子线程要执行的代码放入run()方法中
* 3.currentThread():静态的,调取当前的线程
* 4.getName():获取此线程的名字
* 5.setName():设置此线程的名字
* 6.yield():调用此方法的线程释放当前CPU的执行权
* 7.join():在A线程中调用B线程的join()方法,表示:当执行到此方法,A线程停止执行,直至B线程执行完毕, A线程再接着join()之后的代码执行
* 8.isAlive():判断当前线程是否还存活
* 9.sleep(long l):显式的让当前线程睡眠l毫秒
*
* 10.线程通信:wait() notify() notifyAll()
* //线程通信。如下的三个关键字使用的话,都得在同步代码块或同步方法中。
* //wait():一旦一个线程执行到wait(),就释放当前的锁。
* //notify()/notifyAll():唤醒wait的一个或所有的线程
*
* 设置线程的优先级
* getPriority() :返回线程优先值
* setPriority(int newPriority) :改变线程的优先级