- 需要解决同步问题
- 加入等待与唤醒
- 线程是指程序的运行流程.多线程机制可以同时运行多个程序块,使程序运行效率更高,在每一个线程创建和消亡之前,均会创建,就绪,运行,阻塞,终止状态之一
package study;
import java.lang.*;
import java.util.regex.Pattern;
class Info{
private String name="你好";private String major="2018";
private boolean flag=false;
public synchronized void set(String name,String major){
if(!flag) {
try{
super.wait();
}catch (InterruptedException e){e.printStackTrace();}}
this.setName(name);
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.setMajor(major);
flag=false;
super.notify();
}
public synchronized void get(){
if(flag) {
try{
super.wait();
}catch (InterruptedException e){
e.printStackTrace();
}}
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(this.getName() + "-->" + this.getMajor());
flag=true;
super.notify();
}
public String getMajor() {
return major;
}
public String getName() {
return name;
}
public void setMajor(String major) {
this.major = major;
}
public void setName(String name) {
this.name = name;
}
}
class Producer implements Runnable{
private Info info=null;
public Producer(Info info){
this.info=info;
}
public void run(){
boolean flag=false;
for(int i=0;i<50;i++) {
if (flag) {
this.info.set("你好","2018");
flag=false;
}else{
this.info.set("你不好","2018");
flag=true;
}
}
}
}
class Consumer implements Runnable{
private Info info=null;
public Consumer(Info info){
this.info=info;
}
public void run(){
for(int i=0;i<50;i++){
try{
Thread.sleep(20);
}catch (InterruptedException e){
e.printStackTrace();
}
this.info.get();}
}
}
public class demo {
public static void main(String[] args) {
Info i=new Info();
Producer pro=new Producer(i);
Consumer con=new Consumer(i);
new Thread(pro).start();
new Thread(con).start();
}
}
package study;
import java.lang.*;
import java.util.regex.Pattern;
class Mythread extends Thread{
private int time;
public Mythread (String name,int time){
super(name);
this.time=time;
}
public void run(){
try{
Thread.sleep(this.time);
}catch (InterruptedException e){
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"线程,休眠"+this.time+"毫秒");
}
}
public class demo {
public static void main(String[] args) {
Mythread my1=new Mythread("A",10000);
Mythread my2=new Mythread("B",20000);
my1.start();
my2.start();
}
}
package study;
import java.lang.*;
import java.util.regex.Pattern;
class Mythread implements Runnable{
private int time;
private String name;
public Mythread (String name,int time){
this.name=name;
this.time=time;
}
public void run(){
try{
Thread.sleep(this.time);
}catch (InterruptedException e){
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"线程,休眠"+this.time+"毫秒");
}
}
public class demo {
public static void main(String[] args) {
Mythread my1=new Mythread("A",10000);
Mythread my2=new Mythread("B",20000);
new Thread(my1).start();
new Thread(my2).start();
}
}