定义:同时对多项任务加以控制
继承Thread类
package 多线程;
public class Thread1 extends Thread {
private int baoZi=1;
private String threadName;
public Thread1(String threadName) {
super();
this.threadName = threadName;
}
@Override
public void run() {
while(baoZi<10){
System.out.println(threadName+"在吃第"+baoZi+"个包子");
baoZi++;
}
}
public static void main(String[] args) {
Thread1 thread1=new Thread1("张三线程");
Thread1 thread12=new Thread1("李四线程");
thread1.start();
thread12.start();
}
}
实现Runnable接口
package 多线程;
public class Thread2 implements Runnable {
private int baoZi=1;
private String threadName;
public Thread2(String threadName) {
super();
this.threadName = threadName;
}
@Override
public void run() {
while(baoZi<10){
System.out.println(threadName+"在吃第"+baoZi+"个包子");
baoZi++;
}
}
public static void main(String[] args) {
Thread2 thread1=new Thread2("张三线程");
Thread2 thread12=new Thread2("李四线程");
Thread t11=new Thread(thread1);
Thread t12=new Thread(thread12);
t11.start();
t12.start();
}
}
多线程实现数据共享
package 多线程;
public class Thread3 implements Runnable {
private int baoZi=1;
private String threadName;
public Thread3(String threadName) {
super();
this.threadName = threadName;
}
//上锁synchronized,同一时间只允许一个进程进去执行方法
@Override
public synchronized void run() {
while(baoZi<=10){
System.out.println(threadName+"在吃第"+baoZi+"个包子");
baoZi++;
}
}
public static void main(String[] args) {
Thread3 thread1=new Thread3("超级张三线程");
Thread t11=new Thread(thread1);
Thread t12=new Thread(thread1);
Thread t13=new Thread(thread1);
t11.start();
t12.start();
t13.start();
}
}