实现线程的两种方式
package sdfa;
public class 线程 implements Runnable {
@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i <10; i++) {
try {
Thread.sleep(500);//休眠的时间
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("第"+i+"次执行");
}
}
public static void main(String[] args) {
线程 x= new 线程();
// x.run(); 实现Runnable接口调用线程启动的方法
Thread t=new Thread(x);
t.start();// 基础Thrend类调用线程启动的方法
}
}
线程同步数组买票问题
package sdfa;
import java.util.ArrayList;
import java.util.Scanner;public class 线程1 extends Thread {
public static void main(String[] args) {ArrayList<线程1> tlist = new ArrayList<>();
Object l = new Object();
tlist.add(new 线程1(l));
tlist.add(new 线程1(l));
tlist.add(new 线程1(l));
tlist.add(new 线程1(l));
for (int i = 0; i < tlist.size(); i++) {
tlist.get(i).start();
}
}// public static int a1= 10;
private Object l;//同步锁
public static int a = show();public 线程1(Object l) {
super();
this.l = l;
}
public 线程1() {
}
public void run() {
// sa(show());
sa();
}public void sa() {
while (true) {
try {
Thread.sleep(1000);
synchronized (l) {
if (a > 0) {
a--;
System.out.println(Thread.currentThread().getId());
System.out.println("卖出一张票,还剩" + a + "张票");
}
}
if (a == 0) {
break;
}} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}public static int show() {
System.out.println("请输入一个a值");
Scanner s = new Scanner(System.in);
int a = s.nextInt();
return a;
}
}