Java中的多线程
自用
一、创建线程(方式1)
继承线程类 Thread类 重写 run() 方法
1、设置和获取线程的名称
2、线程中的优先级
public class ThreadDemo {
public static void main(String[] args) {
MyClass s1 = new MyClass();
MyClass s2 = new MyClass();
MyClass s3 = new MyClass();
s1.setName("大G");
s2.setName("BMW");
s3.setName("QQ");
System.out.println(s1.getPriority());
System.out.println(s2.getPriority());
System.out.println(s3.getPriority());
s1.setPriority(6);
// Priority 1-10
s1.start();
s2.start();
s3.start();
}
}
二、创建线程(方式2)
实现 Runnable 接口 此处调用线程名有些不同
public class AnotherClass implements Runnable {
public AnotherClass(){}
@Override
public void run() {
for (int i = 0; i < 100; i++){
System.out.println(Thread.currentThread().getName() + "," + i);
}
}
}
AnotherClass ac1 = new AnotherClass();
AnotherClass ac2 = new AnotherClass();
AnotherClass ac3 = new AnotherClass();
Thread t1 = new Thread(ac1);
Thread t2 = new Thread(ac2);
Thread t3 = new Thread(ac3);
t1.start();
t2.start();
t3.start();
三、多线程中数据安全问题
是否是多线程环境
是否有共享数据
是否有多条语句操作共享数据 (只能在这一点上操作)