JavaSE 多线程
多线程
实现方法
1.继承Tread类
class MyThread extends Thread{
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println("aaaaaaaaa");
}
}
}
public class Demo2_Thread {
public static void main(String[] args) {
MyThread mt = new MyThread();
mt.start();
for (int i = 0; i < 1000; i++) {
System.out.println("bb");
}
}
}
MyThread 继承了 Thread 类,MyThread类重写了Thread 的run方法
在主方法中 创建了一个MyThread的实体类,调用start方法,start方法最终会调用run方法。所以上面的MyThread类中要重写Run方法,为的是将要执行的线程代码放如Run中。
2.重写Runnable接口
class MyRunnable implements Runnable{
@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i < 1000; i++) {
System.out.println("aaaaaaaaaaa");
}
}
}
public class Demo3_Thread {
public static void main(String[] args) {
MyRunnable mr = new MyRunnable();
Thread t = new Thread(mr);
t.start();
for (int i = 0; i < 1000; i++) {
System.out.println("bb");
}
}
}
MyRunnable重写了Runnable接口中的Run方法。
在主方法调用的时候,先定义一个MyRunnable对象,然后定义Thread对象,把MyRunnable的对象传入Thread 中。
将Thread的对象调用start。
3.
new Thread() { //继承Thread类
public void run() { //重写Run方法
for (int i = 0; i < 1000 ; i++) { //将要执行的代码写在Run方法中
System.out.println("aaaaaaaaaa");
}
}
}.start();
直接new一个Thread类,在里面重写Run方法。
new Thread( new Runnable() { //将Runnerble的子类对象传递给Thread的构造方法
public void run() { //重写run方法
for (int i = 0; i < 1000; i++) {
System.out.println("bb");
}
}
}).start();
在Thread类中重写Runnable方法,重写Runnable里面的Run方法。
线程安全
多个线程同步进行穿插运行时,可能会发生 多个线程重复读到一个数据的问题。
synchronized关键字
用来控制线程同步,保证我们在多线程环境下,不被多个线程同时执行,一般加在方法上。
public static synchronized void print1() {
System.out.print("黑");
System.out.print("马");
System.out.print("程");
System.out.print("序");
System.out.print("员");
System.out.println();
}
车站卖票案例
public class Demo3_Ticket {
public static void main(String[] args) {
new Ticket().start();
new Ticket().start();
new Ticket().start();
new Ticket().start();
//开启了四个窗口
}
}
class Ticket extends Thread{
private static int ticket = 100; //为了保证四个窗口调用的票数是同一个数,需要加上static关键字。
@Override
public void run() {
while(true) {
synchronized (Ticket.class) { //此处调用的Synchronized方法是在while循环中,括号中
if(ticket == 0) { //传入的是类名的字节码(class)
break;
}
try { //线程休眠会带来异常,需要try catch
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(getName() + "这是第"+ticket--+"号票");
}
}
}
}
浙公网安备 33010602011771号