一 多线程
(1)就是应用程序有多条执行路径。
进程:就是正在运行的程序。
线程:就是进程的执行路径,执行单元。
(2)如何使用多线程程序:
b:重写Thread类的run()方法。
run()方法里面才是封装线程的代码。
c:通过调用start()方法启动线程并调用run()方法。
代码体现:
public class MyThread extends Thread
{
public void run()
{
for(int x=0; x<100; x++)
{
System.out.println(getName()+"---"+"hello"+x);
}
}
}
public MyThreadTest
{
public static void main(String[] args)
{
MyThread my1 = new MyThread();
MyThread my2 = new MyThread();
my1.start();
my2.start();
}
}
b:重写run()方法
c:创建实现类对象,并把它作为参数传递给Thread类的构造方法,创建Thread对象
d:通过Thread的对象执行
代码体现:
public class MyRunnable implements Runnable
{
public void run()
{
public void run()
{
for(int x=0; x<100; x++)
{
System.out.println(Thread.currentThread().getName()+"---"+"hello"+x);
}
}
}
}
public class MyRunnableTest
{
public static void main(String[] args)
{
MyRunnable my = new MyRunnable();
Thread t1 = new Thread(my);
Thread t2 = new Thread(my);
t1.start();
t2.start();
}
}
(3)线程的随机性原理
多个程序其实是CPU的在做着高效切换执行的。
(4)线程的生命周期
新建
就绪
运行
阻塞
死亡
(5)线程安全问题
a:有共享数据
b:共享数据被多条语句操作
c:在多线程环境中
(6)线程安全问题的解决方案:
A:同步代码块
synchronized(锁对象)
{
被同步的代码
}
B:同步方法
把synchronized加在方法上。
(1)就是应用程序有多条执行路径。
进程:就是正在运行的程序。
线程:就是进程的执行路径,执行单元。
(2)如何使用多线程程序:
A:方式1
继承Thread类。
a:创建类继承Thread类b:重写Thread类的run()方法。
run()方法里面才是封装线程的代码。
c:通过调用start()方法启动线程并调用run()方法。
代码体现:
public class MyThread extends Thread
{
public void run()
{
for(int x=0; x<100; x++)
{
System.out.println(getName()+"---"+"hello"+x);
}
}
}
public MyThreadTest
{
public static void main(String[] args)
{
MyThread my1 = new MyThread();
MyThread my2 = new MyThread();
my1.start();
my2.start();
}
}
B:方式2
实现Runnable接口
a:创建一个类实现Runnable接口b:重写run()方法
c:创建实现类对象,并把它作为参数传递给Thread类的构造方法,创建Thread对象
d:通过Thread的对象执行
代码体现:
public class MyRunnable implements Runnable
{
public void run()
{
public void run()
{
for(int x=0; x<100; x++)
{
System.out.println(Thread.currentThread().getName()+"---"+"hello"+x);
}
}
}
}
public class MyRunnableTest
{
public static void main(String[] args)
{
MyRunnable my = new MyRunnable();
Thread t1 = new Thread(my);
Thread t2 = new Thread(my);
t1.start();
t2.start();
}
}
(3)线程的随机性原理
多个程序其实是CPU的在做着高效切换执行的。
(4)线程的生命周期
新建
就绪
运行
阻塞
死亡
(5)线程安全问题
a:有共享数据
b:共享数据被多条语句操作
c:在多线程环境中
(6)线程安全问题的解决方案:
A:同步代码块
synchronized(锁对象)
{
被同步的代码
}
B:同步方法
把synchronized加在方法上。