一、概念
一个进程就是一个执行中的程序,而每一个进程都有自己独立的一块
内存空间、一组系统资源,每一个进程的内部数据和状态都是完全独立的。
Java程序执行中的单个顺序的流控制称为线程,多线程则指一个进程中可
以同时运行多个不同的线程,执行不同的任务。
二、如何创建多线程
1.继承Thread类
2.实现Runnable接口
- 都需要完成抽象类和接口中为完成的run方法
1.继承Thread类
class MyThread extend Thread
{
void run()
{
int a=10;
System.out.println(a);
}
}
class runMyThread
{
public static void main(String[] args) {
MyThread t =new MyThread();
t.start();
//new MyThread().start()匿名对象
}
}
2.Runnable方法:
class MyThread implements Runnable
{
void run()
{
int a=10;
System.out.println(a);
}
}
class runMyThread
{
public static void main(String[] args) {
MyThread t =new MyThread();
Thread t1=new Thread (t);//Runnable对象必须包含在Thread中
t1.start();
newcThread(new MyThread()).start();//匿名对象
}
}
- 用start启动多线程是并行
- 多个线程对象都start后先启动那个是jvm控制的随机的
- 相比继承Thread类Runnable更好,不占用父类
三、线程间的信息交流
1.static
一般用于Thread类
2.同一个Runnable类的成员变量可以共享
{
MyThread t =new MyThread();
new Thread(t).start();
new Thread(t).start();
new Thread(t).start();
new Thread(t).start();
}
- 生成了四个线程,共享同个MyThread下的成员变量,用的是一个t对象
出现的问题是
1.工作缓冲区
volatile更改线程中的数据,所有线程都更改。让所有线程都能看到
2.关键步骤需要加锁
synchronized控制每次只能进一个线程
public class ThreadDemo3 {
public static void main(String[] args) {
TestThread3 t = new TestThread3();
new Thread(t, "Thread-0").start();
new Thread(t, "Thread-1").start();
new Thread(t, "Thread-2").start();
new Thread(t, "Thread-3").start();
}
}
class TestThread3 implements Runnable {
private volatile int tickets = 100; // 多个 线程在共享的
String str = new String("");
public void run() {
while (true) {
sale();
try {
Thread.sleep(100);
} catch (Exception e) {
System.out.println(e.getMessage());
}
if (tickets <= 0) {
break;
}
}
}
public synchronized void sale() { // 同步函数
if (tickets > 0) {
System.out.println(Thread.currentThread().getName() + " is saling ticket " + tickets--);
}
}
}