java 多线程创建的两种方式
1:estends Thread 类
public class hacker_01_MyThread extends Thread {
public hacker_01_MyThread(String name) {
super(name);
}
@Override
public void run() {
System.out.println(this.getName()+"正在执行。。。");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(this.getName()+"执行完成。。。");
}
}
调用
public class hacker_02_MyThreadDemo {
public static void main(String[] args) {
for (int i=0;i<100;i++)
{
hacker_01_MyThread thread = new hacker_01_MyThread("线程" + i);
thread.start();
}
System.out.println("主线程结束。。。");
}
}
2:new Thread(Runnable接口实现类)
最常用第二种方式,类可以实现多个接口,类只能继承一个父类
public class hacker_03_RunableImpl1 implements Runnable{
@Override
public void run() {
System.out.println("线程执行")
}
}
调用
public class hacker_03_RunableImpleDemo {
public static void main(String[] args) {
// Runable接口的实现类
hacker_03_RunableImpl1 hacker_03_runable1 = new hacker_03_RunableImpl1();
for(int i=0;i<3300;i++){
new Thread(hacker_03_runable1).start();
}
System.out.println("主线程结束。。。");
}
}
实现Runnable接口的实现对象,当被多次start会创建多个多个线程执行,共享成员变量,造成线程不安全问题。
解决方式:一种同步代码块,一种同步方法,一种锁对象
public class hacker_03_RunableImpl1 implements Runnable{
private int ticket=100;
//锁对象
private Object obj=new Object();
@Override
public void run() {
// 第一种保证同步,synchronized同步代码块
synchronized(obj){
if (ticket >0){
--ticket;
System.out.println("现在正在卖"+ticket+"张");
}
}
}
}
public class hacker_03_RunableImpl2 implements Runnable {
private int ticket=10000;
@Override
public void run() {
SaleTicket();
}
// 第二种保证同步,同步方法
private /*synchronized*/ void SaleTicket(){
if(this.ticket>0){
System.out.println("现在正在卖第"+ticket);
this.ticket=--this.ticket;
}
}
}
public class hacker_03_RunableImpl3 implements Runnable{
private int ticket=10000;
// 多态
private Lock I =new ReentrantLock();
@Override
public void run() {
// 第三种保证同步,锁对象
// I.lock();
System.out.println("现在正在卖第"+ticket+"张票");
--ticket;
// I.unlock();
}
}