1.继承Thread类。
2.实现Runnable接口。
package com.java.test;
/***
* 继承Thread类实现多线程
* @author Administrator
*
*/
public class Thread01 extends Thread {
private int ge=1;
private String threadName;
public Thread01(String threadName) {
super();
this.threadName = threadName;
}
@Override
public void run() {
while(ge<=10){
System.out.println(threadName+" 唱第"+ge+"首歌");
ge++;
}
}
public static void main(String[] args) {
// 开启:小明、小王两个线程,每个线程唱10首歌
Thread01 t1=new Thread01("小明线程");
Thread01 t2=new Thread01("小王线程");
t1.start();
t2.start();
}
}
运行输出:
小明线程 唱第1首歌
小王线程 唱第1首歌
小明线程 唱第2首歌
小王线程 唱第2首歌
小明线程 唱第3首歌
小王线程 唱第3首歌
小明线程 唱第4首歌
小明线程 唱第5首歌
小明线程 唱第6首歌
小明线程 唱第7首歌
小明线程 唱第8首歌
小明线程 唱第9首歌
小明线程 唱第10首歌
小王线程 唱第4首歌
小王线程 唱第5首歌
小王线程 唱第6首歌
小王线程 唱第7首歌
小王线程 唱第8首歌
小王线程 唱第9首歌
小王线程 唱第10首歌
package com.java.test;
/**
* 继承Runnable接口实现多线程
* @author Administrator
*
*/
public class Thread02 implements Runnable{
private int ge=1;
private String threadName;
public Thread02(String threadName) {
super();
this.threadName = threadName;
}
@Override
public void run() {
while(ge<=10){
System.out.println(threadName+" 唱第"+ge+"首歌");
ge++;
}
}
public static void main(String[] args) {
//最终输出结果多是一样的
Thread02 t1=new Thread02("小明线程");
Thread02 t2=new Thread02("小王线程");
Thread t11=new Thread(t1);
Thread t12=new Thread(t2);
t11.start();
t12.start();
}
}
在上面的实现方式肯定看到了,数据的不统一。
多线程数据共享实现:
package com.java.test;
public class Thread03 extends Thread{
private int ge=1;
private String threadName;
public Thread03(String threadName) {
super();
this.threadName = threadName;
}
/**
* 实现数据共享关键字synchronized
*/
@Override
public synchronized void run() {
while(ge<=10){
System.out.println(threadName+" 唱第"+ge+"首歌");
ge++;
}
}
public static void main(String[] args) {
Thread03 t1=new Thread03("小红线程");
Thread t11=new Thread(t1);
Thread t12=new Thread(t1);
Thread t13=new Thread(t1);
t11.start();
t12.start();
t13.start();
}
}
运行结果:
小红线程 唱第1首歌
小红线程 唱第2首歌
小红线程 唱第3首歌
小红线程 唱第4首歌
小红线程 唱第5首歌
小红线程 唱第6首歌
小红线程 唱第7首歌
小红线程 唱第8首歌
小红线程 唱第9首歌
小红线程 唱第10首歌
定义一个实例 然后用这个实例来是实例化三个Thread对象,run方法我们要加synchronized锁,
否则会出现多个线程同时进入方法的情况,导致多个线程吃同一个包子的状况;