目录
一:实现多线程的两种方式:
1、继承Thread类
public class TestThread {
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName());
Thread t1 = new MyThread("A");
Thread t2 = new MyThread("B");
Thread t3 = new Thread(new MyThread("C"));//线程交由别的线程来执行
t1.start();
t2.start();
t3.start();
}
}
class MyThread extends Thread{
private String name;
public MyThread() {}
public MyThread(String name) {
this.name=name;
}
@Override
public void run() {
System.out.println("当前线程"+name);
}
}
结果打印:
main
当前线程A
当前线程C
当前线程B
线程的执行顺序与代码调用顺序无关。且不可以直接调用run方法,直接调用run方法时就不是异步执行了,而是同步,此时由main线程直接调用run方法,而不是将此线程对象交给“线程规划器”来处理。
2、实现Runnable接口
Thread类中有两个构造方法Thread(Runnable target)和Thread(Runnable target, String name)支持传递Runnable接口。
class MyRunnable implements Runnable{
@Override
public void run() {
System.out.println("运行的过程");
}
}
public class TestThread {
public static void main(String[] args) {
Runnable r = new MyRunnable();
Thread t = new Thread(r);
t.start();
}
}
二:实例变量与线程安全
自定义的线程类中的实例变量可以有共享和不共享两种。
不共享时:线程各自调用各自的实例变量
共享时:
例子:线程调用具有随机性,如下创建一个线程类。
public class ShareTest {
public static void main(String[] args) {
ShareThread st = new ShareThread(); //创建一个线程由多个线程调用
Thread a = new Thread(st,"A"); //分配Thread对象,作为运行对象,指定name
Thread b = new Thread(st,"B");
Thread c = new Thread(st,"C");
Thread e = new Thread(st,"E");
Thread d = new Thread(st,"D");
a.start();
b.start();
c.start();
d.start();
e.start();
}
}
class ShareThread extends Thread {
private int count=5;
@Override
public void run() {
count--;
System.out.println("由"+this.currentThread().getName()+"计算,count="+count);
}
}
由于在JVM中,执行i--操作时,分为3步,1、取得i值 2、执行i-- 3、写回i值,
所以,多个线程访问时,就会出现非线程安全问题
在run方法前加上关键字synchronized关键字,当一个线程调用run方法时,先判断有没有上锁,上锁时,要等待其他线程调用run方法结束,才能执行run方法。synchronized可以对任意对象和方法上锁,加锁的代码成为“互斥区”或“临界区”。
public class ShareTest {
public static void main(String[] args) {
ShareThread st = new ShareThread();
Thread a = new Thread(st,"A");
Thread b = new Thread(st,"B");
Thread c = new Thread(st,"C");
Thread e = new Thread(st,"E");
Thread d = new Thread(st,"D");
a.start();
b.start();
c.start();
d.start();
e.start();
}
}
class ShareThread extends Thread {
private int count=5;
@Override
public synchronized void run() {
count--;
System.out.println("由"+this.currentThread().getName()+"计算,count="+count);
}
}
运行结果:
1、线程类常用方法:
Thread.currentThread().getName() 获取当前运行线程的名字
public class Test {
public static void main(String[] args) {
ThreadTest t1 = new ThreadTest();
ThreadTest t2 = new ThreadTest();
t1.start();
t2.run();
}
}
class ThreadTest extends Thread {
public ThreadTest() {
System.out.println("构造方法+"+Thread.currentThread().getName());
}
@Override
public void run() {
System.out.println("run方法+"+Thread.currentThread().getName());
}
}
执行结果如下:创建thread时,main方法执行,直接调用run方法时,也是main方法进行调用的,不是线程规划器。手动调用run就不是多线程异步执行了。
isAlive()判断当前线程是否处于活动状态
sleep() 让“正在执行的线程休眠”指定的毫秒数,这个线程是this.currentThread()返回的线程
getId() 获取线程的唯一标识。