1.线程的创建的两种方法
1.1.用Thread
public class MyThread extends Thread{
public void run(){
//.....
}
}
//启动
MyThread thread=new MyThread();
thread.start();
1.2.用Runnable
public class Aoo implements Runnable{
public void run(){
//....
}
}
//启动
Thread thread =new Thread(new Aoo());
thread.start();
2.线程的三种主要状态
就绪ready
运行running
阻塞block
3.常用的方法
3.1.static Thread currentThread(); 返回对当前正在执行的线程对象的引用
3.2.int getPriority(); 返回线程的优先级
3.3.void setPriority(int newPriority);更改线程的优先级
3.4.boolean isDaemon(); 测试该线程是否为守护线程
3.5.void setDaemon(boolean on); 将该线程标记为守护线程true或用户线程false
3.6.static void sleep(long millis); 线程休眠,暂停时间为毫秒数,时间到之后进入就绪状态
3.7.static void yield(); 暂停当前正在执行的线程对象,立即进入就绪状态
3.8.void join(); 进入阻塞状态,等待该线程终止
4.守护线程
void setDaemon(boolean on);//false
当jvm发现所有的线程都是守护线程的时候,自动退出
5.线程同步问题
5.1.两个以上线程同时修改一个对象,产生同步问题
5.2.解决同步问题:对两个以上线程共同调用的对象进行加锁
这样一个线程调用完同步代码块另一个线才能去调用
5.3.同步代码块:
synchronized(任何一个对象都可以){
// 多个线程修改的代码
}
5.4.同步代码块的范围要合适
5.5.一个对象可以加锁多个代码块,这些代码块作为一个整体被加锁
6.线程安全类
6.1.两个以上线程同时访问该类的一个对象,不会有线程同步问题
6.2.线程安全类的两个种类:
1).不可变类 例如:String,所有包装类
2).可变类 但是 synchronized 修饰了 例如:StringBuffer
6.3.线程安全类在单线程的时候运行效率低
7.非线程安全类
7.1.例如以下是非线程安全类
StringBuilder
ArrayList
HashMap
7.2.非线程安全类在单线程的时候运行效率高
7.3.转换为线程安全类
Collections.synchronizedList(List<T> list);//list
Collections.synchronizedMap(Map<K,V> m);//map
Collections.synchronizedSet(Set<T> s);//set
例子:
List<String> list = new ArrayList<String>();
List<String> list1 = Collections.synchronizedList(list);
package testjavase;
public class ThreadDemo
{
// 测试
public static void main(String[] args) throws Exception
{
Object obj = new Object();
// 启动两个线程
Thread1 t1 = new Thread1(obj);
Thread2 t2 = new Thread2(obj);
t1.start();
t2.start();
}
}
// 一个线程打印1-52
class Thread1 extends Thread
{
private Object obj;
public Thread1(Object obj)
{
this.obj = obj;
}
public void run()
{
synchronized (obj)
{
// 打印1-52
for (int i = 1; i < 53; i++)
{
System.out.print(i + " ");
if (i % 2 == 0)
{
// 不能忘了 唤醒其它线程
obj.notifyAll();
try
{
obj.wait();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
}
}
// 另一个线程打印字母A-Z
class Thread2 extends Thread
{
private Object obj;
public Thread2(Object obj)
{
this.obj = obj;
}
public void run()
{
synchronized (obj)
{
// 打印A-Z
for (int i = 0; i < 26; i++)
{
System.out.print((char)('A' + i) + " ");
// 不能忘了 唤醒其它线程
obj.notifyAll();
try
{
// 最后一个就不要等了
if (i != 25)
{
obj.wait();
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
}