1.继承Thread类
class MyThread extends Thread{
private String title;
public MyThread(String title){
this.title = title;
}
public void run(){
for(int i=0; i<10 ;i++){
System.out.println(this.title + "线程:"+i);
}
}
}
public class ThreadDemo {
public static void main(String[] args){
new Thread(new MyThread("一")).start();
new Thread(new MyThread("二")).start();
new Thread(new MyThread("三")).start();
}
}
2.实现Runnable接口
class MyThread implements Runnable{
private String title;
public MyThread(String title){
this.title = title;
}
public void run(){
for(int i=0; i<10 ;i++){
System.out.println(this.title + "线程:"+i);
}
}
}
public class ThreadDemo {
public static void main(String[] args){
new Thread(new MyThread("一")).start();
new Thread(new MyThread("二")).start();
new Thread(new MyThread("三")).start();
//因为Runnable接口是一个函数接口,所有可以使用lambda实现
for(int i=0; i<3 ; i++){
String title = "线程:"+ i;
new Thread(()->{
for(int k=0; k<10; k++){
System.out.println(title+"运行:"+k);
}
}).start();
}
}
3.Callable接口实现java.util.concrrent包中
class MyThread implements Callable<String> {
@Override
public String call() throws Exception {
for(int i = 0; i<10; i++){
System.out.println("线程执行中");
}
return "线程执行完成";
}
}
public class MyThreadDemo{
public static void main(String args[]){
FutureTask<String> fun = new FutureTask<String>(new MyThread());
new Thread(fun).start();
try {
System.out.println("返回值"+fun.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
4.线程同步 synchronized
class TicketDemo implements Runnable {
@Override
public void run() {
while (true){
// synchronized (this){//线程同步
// }
if(this.payTickeStaitc()){
break;
}
}
}
public int count = 10;//票数
public synchronized boolean payTickeStaitc(){
if(this.count > 0){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() +"卖出一张,还剩" + this.count--);
return false;
}else{
System.out.println("票买完了");
return true;
}
}
}
public class Ticket{
public static void main(String[] args){
TicketDemo ticketDemo = new TicketDemo();
Thread threadA =new Thread(ticketDemo,"买票1");
Thread threadB =new Thread(ticketDemo,"买票2");
Thread threadC =new Thread(ticketDemo,"买票3");
threadA.start();
threadB.start();
threadC.start();
}
}
5.线程中断
public static void main(String[] args){
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("劳资要休息");
try {
Thread.sleep(1000);
System.out.println("休息够了");
} catch (InterruptedException e) {
System.out.println("打扰劳资睡觉");
}
}
});
thread.start();
if(!thread.isInterrupted()){
thread.interrupt();
}
}